Laravel belongsTo 关系从 with 方法返回空对象
Laravel belongsTo Relationship returning null object from with method
我想使用 jQuery 数据表制作一个列表。但是我有以下用法的问题。
我的储备模型:
//Reserve Author
public function author(){
return $this->belongsTo(User::class, 'author_id');
}
//Reserver
public function reserver(){
return $this->belongsTo(User::class, 'reserver_id');
}
//Stock
public function stock(){
return $this->belongsTo(Stock::class, 'reference_id', 'code')->where('company_id', $this->company_id);
}
以下用法成功
$reserve = Reserve::find(id);
$reserve->stock->name;
但是这种用法不起作用:
Reserve::with('reserver','author', 'stock')->get()->toJson();
在此代码中,服务器和作者关系有效,但库存返回空对象。我究竟做错了什么?如果你能帮助我,我会很高兴。谢谢
我用不同的方法解决了这个问题。我习惯了每一种方法,现在开始工作了。
Reserve::with('reserver','author')->get()->each(function($q){
$q->setAttribute('stock', $q->stock->toArray());
})->toJson();
如果有更好的方法我也想用。谢谢
我想使用 jQuery 数据表制作一个列表。但是我有以下用法的问题。
我的储备模型:
//Reserve Author
public function author(){
return $this->belongsTo(User::class, 'author_id');
}
//Reserver
public function reserver(){
return $this->belongsTo(User::class, 'reserver_id');
}
//Stock
public function stock(){
return $this->belongsTo(Stock::class, 'reference_id', 'code')->where('company_id', $this->company_id);
}
以下用法成功
$reserve = Reserve::find(id);
$reserve->stock->name;
但是这种用法不起作用:
Reserve::with('reserver','author', 'stock')->get()->toJson();
在此代码中,服务器和作者关系有效,但库存返回空对象。我究竟做错了什么?如果你能帮助我,我会很高兴。谢谢
我用不同的方法解决了这个问题。我习惯了每一种方法,现在开始工作了。
Reserve::with('reserver','author')->get()->each(function($q){
$q->setAttribute('stock', $q->stock->toArray());
})->toJson();
如果有更好的方法我也想用。谢谢