I want to make a list using jQuery datatable. But I have a problem with the following usage.
My Reserve Model:
//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);
}
Following usage is working successfully
$reserve = Reserve::find(id);
$reserve->stock->name;
But this usage is not working:
Reserve::with('reserver','author', 'stock')->get()->toJson();
Reserver and author relationship are working in this code but stock is returning null object. What am I doing wrong? I'll be happy if you can help me. Thanks.
I solved the problem in a different way. I used to each method and now working.
Reserve::with('reserver','author')->get()->each(function($q){
$q->setAttribute('stock', $q->stock->toArray());
})->toJson();
I would like to use it if there is a better method. Thanks.