Laravel 5.1 - 通过多个表加入

Laravel 5.1 - Join through multiple tables

我有以下表格:

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

那'belongsToMany'呢? 例如。像

$customer->belongsToMany('OrderNote', 'orders', 'customer_id', 'id');

当然不能直接使用,如果你也想获取order对象(但也许你可以使用withPivot

在您的模型上创建这些关系。

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

最后我只是做了以下事情:

class Customer extends Model
{
    public function order_notes()
    {
        return $this->hasManyThrough('App\Order_note', 'App\Order');
    }
}

class Order_note extends Model
{
    public function order()
    {
        return $this->belongsTo('App\Order');
    }

    public function note()
    {
        return $this->belongsTo('App\Note')->orderBy('notes.id','desc');
    }
}

然后像这样访问笔记:

@foreach($customer->order_notes as $note)
    echo $note->note->text;
@endforeach