I have three models namely Header, Details, Item. The Header have id , customer_id , the Details have id , header_id (FOREIGN KEY) , and item_id (FOREIGN KEY) , and the Item have id , name . Now, I want to relate that tables using laravel eloquent relationships. I've been able to do that with:
class Details extends Model
{
public function item() {
return $this->belongsTo('App\Item', 'bill_item_id');
}
public function header() {
return $this->belongsTo('App\Header', 'header_id');
}
}
The problem is in my controller, I want to get the details but details don't have customer_id.
$detail = Details::where('customer_id', $id)->get();
$detail->load('header', 'item');
The customer_id field is in the header model. if I get all the details, it's working fine but I want to get specific customer.
Write your code like this
$details = Details::with('header')->where('customer_id', $id)->get();
OR
$details = Details::with(['header'=>function($query) use ($id){
$query->where('customer_id', $id);
}])->get()
This will get result depended on your relation.
you can use with for where the field in relation
Details::with([ 'header' => function($query) use ($id) {$query->where('customer_id', $id);}])->get();
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.