php – Laravel 5.1 – 通过多个表加入

我有以下表格:

Customer
    id

Order
    id
    customer_id

Order_notes
    order_id
    note_id

Notes
    id

如果我想获得客户的所有订单备注,那么我可以执行以下操作,我该怎么办?有没有办法在我的模型中定义一个关系,通过多个数据透视表来加入客户订购笔记?

@if($customer->order_notes->count() > 0)
    @foreach($customer->order_notes as $note)
        // output note
    @endforeach
@endif

最佳答案 在模型上创建这些关系.

class Customer extends Model
{
    public function orders()
    {
        return $this->hasMany(Order::class);
    }

    public function order_notes()
    {
        // have not tried this yet
        // but I believe this is what you wanted
        return $this->hasManyThrough(Note::class, Order::class, 'customer_id', 'id');
    }
}

class Order extends Model
{
    public function notes()
    {
        return $this->belongsToMany(Note::class, 'order_notes', 'order_id', 'note_id');
    }
}

class Note extends Model
{

}

您可以使用此查询获取关系:

$customer = Customer::with('orders.notes')->find(1);
点赞