简体   繁体   English

Laravel雄辩的急切加载假定不正确的数据透视表列名称

[英]Laravel Eloquent Eager Loading assumes incorrect pivot table column name

I have two tables in Laravel 5.4. 我在Laravel 5.4中有两个表。 Orders and Product which are joined by a many-to-many relationship 通过多对多关系加入的订单和产品

I'm trying to fetch all the orders together with the associated products like so: 我正在尝试获取所有订单以及相关产品,如下所示:

$orders = Orders::with('products')->get();

My Order Model has this set up as 我的订单模型将此设置为

public function products()
{
    return $this->belongsToMany('App\Product')
        ->withPivot('qty')
        ->withTimeStamps();
}

When I output the log I get the following error message: 当我输出日志时,出现以下错误消息:

Next Illuminate\Database\QueryException: SQLSTATE[42S22]: Column not found: 1054 Unknown column 'order_product.order_order_id' in 'field list' (SQL: select `products`.*, `order_product`.`order_order_id` as `pivot_order_order_id`, `order_product`.`product_product_id` as `pivot_product_product_id`, `order_product`.`qty` as `pivot_qty`, `order_product`.`created_at` as `pivot_created_at`, `order_product`.`updated_at` as `pivot_updated_at` from `products` inner join `order_product` on `products`.`product_id` = `order_product`.`product_product_id` where `order_product`.`order_order_id` in (66, 67, 70, 72, 73, 74) and `products`.`deleted_at` is null) in /home/vagrant/Projects/vcc-backoffice/vendor/laravel/framework/src/Illuminate/Database/Connection.php:647

The issue is that Laravel is looking for a table in the Pivot called " order_order_id " which doesn't exist. 问题在于Laravel在数据透视表中查找一个名为“ order_order_id ”的表,该表不存在。 I haven't declared the column to be called that. 我还没有宣布要称为该列。 My pivot table columns are called " order_id " and " product_id " 我的数据透视表列称为“ order_id ”和“ product_id

I don't know how Laravel assumes the pivot table names. 我不知道Laravel如何假定数据透视表的名称。 Is there a way to specifically declare the column names in the pivot? 有没有一种方法可以在数据透视表中专门声明列名称? Or have I made a mistake in my naming conventions? 还是我在命名约定方面犯了错误?

If you have two model named Order & Product and many_to_many relationship between them and their database table like orders & products then Laravel will search for a pivot table named order_product (model name in alphabetic order and joined by '_' ). 如果你有两个型号命名OrderProduct ,并将它们和喜欢他们的数据库表之间的关系MANY_TO_MANY ordersproducts然后Laravel将搜索数据透视表名为order_product (型号名称字母顺序和“_”加入)。
order_product table will composed of two columns order_id , product_id . order_product表将由两列order_idproduct_id This is the basic naming convention for pivot table in a nutshell :) . 简而言之,这是数据透视表的基本命名约定:)。

Edit Order Model and try following code : 编辑订单模型,然后尝试以下代码:

public function products()
{
    return $this->belongsToMany('App\Product','order_product','order_id','product_id')
        ->withPivot('qty')
        ->withTimeStamps();
}

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

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