2015-10-05 73 views
4

加入我有以下表格: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 
+0

你只想要你的模型? – AndreL

+0

不一定,只是想知道最好的方法是 – geoffs3310

回答

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 
0

怎么样'belongsToMany'? 例如像

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

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

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

我不认为这是我想要的,因为这将单独返回所有订单,然后记录每个订单。我只想要一个代表所有客户订单记录的bug对象 – geoffs3310

+0

这正是@ sumpreto的代码所做的。你只需要使用'@foreach($ customer-> notes作为$ notes)',你就可以走了。 – charlesrockbass

+0

@ geoffs3310我在Customer模型下添加了一个方法。还没有尝试过,但我认为它可能工作。 – sumpreto