Laravel 5.1 - 通过多个表加入

时间:2015-10-05 09:35:45

标签: php laravel laravel-5 eloquent 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

3 个答案:

答案 0 :(得分:2)

在模型上创建这些关系。

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

答案 1 :(得分:0)

怎么样&属于他妈的' ? 例如。

之类的东西
$customer->belongsToMany('OrderNote', 'orders', 'customer_id', 'id');

当然,如果你想获得订单对象,它也不会直接工作(但也许你可以使用withPivot

答案 2 :(得分:0)

最后我刚刚做了以下事情:

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