简体   繁体   English

雄辩的:与laravel 5中的3个表的关系

[英]Eloquent: Relationships with 3 tables in laravel 5

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 . 标头具有idcustomer_id详细信息具有idheader_id(FOREIGN KEY)item_id(FOREIGN KEY) ,而Item具有idname Now, I want to relate that tables using laravel eloquent relationships. 现在,我想使用laravel雄辩的关系来关联这些表。 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. 问题出在我的控制器中,我想获取详细信息,但是详细信息没有customer_id。

$detail = Details::where('customer_id', $id)->get();
$detail->load('header', 'item');

The customer_id field is in the header model. customer_id字段位于标头模型中。 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 您可以将with用于与之相关的字段

Details::with([ 'header' => function($query) use ($id) {$query->where('customer_id', $id);}])->get(); 详细信息:: with([[标头=>函数($ query)使用($ id){$ query-> where('customer_id',$ id);}])-> get();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM