Laravel 5.2 hasManyThrough 关系问题

Laravel 5.2 hasManyThrough relationship issue

我有 3 个 table:订单、代码、事件

我希望能够提取一个订单中的所有事件,但有一个中介 table 作为枢轴 table。我一直在尝试使用 hasManyThroughbelongsToMany(以及 withPivot),但没有任何运气。

示例:

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
}

任何指点都会很棒!

这是一个 belongsToMany 设置。首先,第一个参数是相关的名称class。其次,由于您的枢轴 table 不遵循 Laravel 命名约定,您需要在关系定义中指定枢轴 table 的名称:

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

使用此设置,您可以:

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

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

有很多方法可以做到这一点。我会展示一个你可以完成的。

Order.php模型中

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

Code.php模型中

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

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

Event.php模型中

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

然后在你的控制器中,调用它们来获取所需的数据。

在你的情况下,你可以像下面那样做:

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

也许你可以用嵌套的方式得到它们(不确定这个,因为我在发布之前没有尝试过):

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

return $orders; 放入您的控制器中以查看查询。

尽情享受吧!