繁体   English   中英

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

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

我有三个模型,分别是标题,详细信息和项目。 标头具有idcustomer_id详细信息具有idheader_id(FOREIGN KEY)item_id(FOREIGN KEY) ,而Item具有idname 现在,我想使用laravel雄辩的关系来关联这些表。 我已经能够做到这一点:

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');
    }
}

问题出在我的控制器中,我想获取详细信息,但是详细信息没有customer_id。

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

customer_id字段位于标头模型中。 如果我了解所有详细信息,说明一切正常,但我想获得特定的客户。

这样写你的代码

$details = Details::with('header')->where('customer_id', $id)->get();

要么

$details = Details::with(['header'=>function($query) use ($id){
    $query->where('customer_id', $id);
}])->get()

这将取决于您的关系而得出结果。

您可以将with用于与之相关的字段

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

暂无
暂无

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

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