Laravel 属于多通过多

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/25184401/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 09:54:59  来源:igfitidea点击:

Laravel Belongs to Many Through multiple

phplaraveleloquentrelationship

提问by Jordi Puigdellívol

I have the following table structure

我有以下表结构

turns
id


id

orders_payments
id
turn_id
order_id

orders_payments
id
turn_id
order_id

orders
id

订单
编号

And I want to get all orders related to a turn

我想获得与转弯相关的所有订单

so

所以

Class Turn{
  public function orders(){
      return ????
  }

}

How can you achieve that? I tried the hasmanythroughbut it only works when the relations are in cascade

你怎么能做到这一点?我试过了,hasmanythrough但它只在关系级联时有效

Thanks!

谢谢!

回答by Jarek Tkaczyk

I wonder why you make your life hard and call your model Turnand the pivot table order_payment?

我想知道为什么你让你的生活变得艰难并称你的模型Turn和数据透视表order_payment

Anyway, you want this:

无论如何,你想要这个:

// Turn model
public function orders()
{
   return belongsToMany('Order', 'order_payment');
   // in case you would like to call your fkeys differently, use this:
   // return belongsToMany('Order', 'order_payment', 'payment_id', 'order_whatever_id');
}

// Order model
public function turns() // or payments() ?
{
   return belongsToMany('Turn', 'order_payment');
}

回答by lowerends

You can use

您可以使用

public function orders()
{
    return $this->belongsToMany('Order');
}

Then you can do

然后你可以做

$orders = Turn::find(1)->orders;

回答by Jordi Puigdellívol

As @lowerends points out, this is a BelongsToMany relationship, since I was using the orderPayments table for more things I didn't notice it until he said, so finally the solution is the following

正如@lowerends 指出的那样,这是一个 BelongsToMany 关系,因为我使用 orderPayments 表处理更多事情,直到他说我才注意到它,所以最后的解决方案如下

```

``

public function orders(){
    return $this->belongsToMany('Order','orders_payments','turn_id','order_id');
}

```

``