雄辩的关系返回null,但类似的关系很好

雄辩的关系返回null,但类似的关系很好

问题描述:

使用Lumen 5.5.2和illuminate/database v5.5.17。雄辩的关系返回null,但类似的关系很好

我有3个模型设置,其中一个属于另一个2.所以报价,有一个区域和一个仓库。

与仓库的关系按预期工作,该区域返回null。

例如

$quoteModel = new Quote();   
    $quote = $quoteModel 
      ->with('area') 
      ->with('depot') 
      ->where('id', '=', $id) 
      ->first(); 


    echo 'depot id : ' , $quote->depot->id , "<br>\n"; 
    echo 'area id : ' , $quote->area->id , "<br>\n"; 

贮库ID会被回荡,因为它不是一个对象的区域将导致错误。

将模型名称作为数组​​传递,或者只是请求区域(两种方法)都不能解决此问题。

Quote.php

namespace App\Models; 

use Illuminate\Database\Eloquent\Model as EloquentModel; 

class Quote extends EloquentModel { 

    protected $table = 'quotes'; 

    public function area() { 
     return $this->belongsTo('\App\Models\Area', 'area_id', 'id'); 
    } 

    public function depot() { 
     return $this->belongsTo('\App\Models\Depot', 'depot_id', 'id'); 
    } 

} 

Area.php

namespace App\Models; 

use Illuminate\Database\Eloquent\Model as EloquentModel; 

class Area extends EloquentModel { 

    protected $table = 'areas'; 

    public $timestamps = false; 
    public $incrementing = false; 

    public function quotes() { 
     return $this->hasMany('\App\Models\Quote', 'area_id', 'id'); 
    } 

} 

Depot.php

namespace App\Models; 

use Illuminate\Database\Eloquent\Model as EloquentModel; 

class Depot extends EloquentModel { 

    protected $table = 'depots'; 

    public $timestamps = false; 
    public $incrementing = false; 

    public function quotes() { 
     return $this->hasMany('\App\Models\Quote', 'depot_id', 'id'); 
    } 

} 

如果我在Area.php创建一个解析错误,脚本将失败,证明它正在被包括在内。

我有一个监听器,所以我可以记录查询,他们显示出来很好。

select * from `quotes` where `id` = 99192 limit 1 
select * from `areas` where `areas`.`id` in (072) 
select * from `depots` where `depots`.`id` in (07) 

如果我手动运行区域查询,它将返回我期望的行。

我试着改变区域关系的名称,但它没有帮助。

+1

你使用了什么雄辩的版本?你可以试试 - > with(['area','depot'])而不是链接它们吗? – matiit

+0

感谢您对版本的提醒。它们是写作时最新的(我在5.4版本,升级没有帮助或伤害) - 我更新了我的问题。可悲的阵列语法没有帮助 – CodeMonkey

因此,这个难题的缺点是,该项目是针对遗留数据库建立的,作为更新现有Web应用程序的一部分。

原来,有一些数据类型不一致;当我能够成功地将另一个模型链接到没有问题的区域时,我发现了这一点。 area_id的字段通常是零填充int,但由于某种原因,在引号表中它是一个char;所以当在adminer中浏览时数据看起来是正确的,并且在复制和粘贴时工作,但在Eloquents内部的某处不匹配。

更改表格上的数据类型可以解决问题。

+0

很高兴看到你明白了! – matiit