简体   繁体   English

Laravel 5.2 hasManyThrough关系问题

[英]Laravel 5.2 hasManyThrough relationship issue

I have 3 tables: orders, codes, events 我有3张桌子:订单,代码,事件

I want to be able to pull all events that an order has, but there's an intermediary table that acts as a pivot table. 我希望能够提取订单中的所有事件,但是有一个中间表充当数据透视表。 I've been trying to use hasManyThrough and belongsToMany (along with withPivot ) without any luck. 我一直在尝试使用hasManyThroughbelongsToMany (以及withPivot ),但没有任何运气。

Examples: 例子:

public function events()
{
    return $this->belongsToMany('events'); // tried this, fails
    return $this->hasManyThrough('events', 'codes'); // tried this, fails
    return $this->hasManyThrough('events', 'codes', 'event_id', 'id'); // tried this, fails
}

Any pointers would be great! 任何指针都很棒!

示例图片

That's a belongsToMany setup. 那是一个belongsToMany设置。 First, the first parameter is the name of the related class. 首先,第一个参数是相关类的名称。 Second, since your pivot table doesn't follow the Laravel naming conventions, you need to specify the name of the pivot table in your relationship definition: 其次,由于数据透视表不遵循Laravel命名约定,因此需要在关系定义中指定数据透视表的名称:

public function events()
{
    // first parameter is the name of the related class
    // second parameter is pivot table name
    return $this->belongsToMany(Event::class, 'codes');
}

With this setup, you can do: 使用此设置,您可以执行以下操作:

// get an order
$order = Order::first();

// has all the events related to an order
$events = $order->events;

There are many ways to do this. 有很多方法可以做到这一点。 I will show a one you can get it done. 我将展示一个您可以完成的任务。

In Order.php model Order.php模型中

public function codes(){
   return $this->has('App\Http\Code');
}

In Code.php model Code.php模型中

public function orders(){
   return $this->belongsTo('App\Http\Order');
}

public function events(){
   return $this->hasMany('App\Http\Event');
}

In Event.php model Event.php模型中

public function codes(){
   return $this->belongsTo('App\Http\Code');
}

Then in you Controller, call them to get required data. 然后在Controller中,调用它们以获取所需的数据。

In your case you can do it like below: 您可以按照以下方式进行操作:

$orders = Order::with(['codes' => function($q){
    $q->with('events');
})->get();

May be you can get them with nested manner(not sure about this because i didn't tried before posting): 也许您可以嵌套的方式获取它们(不确定这一点,因为我在发布之前没有尝试过):

$orders = Order::with('codes.events')->get();

put return $orders; 放置return $orders; in your controller to see the query. 在您的控制器中查看查询。

Enjoy! 请享用!

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

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