[英]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();
如果有更好的方法,我想使用它。 谢谢。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.