【问题标题】:Laravel Eloquent Eager Loading assumes incorrect pivot table column nameLaravel Eloquent Eager Loading 假定数据透视表列名不正确
【发布时间】:2018-01-19 01:09:44
【问题描述】:

我在 Laravel 5.4 中有两个表。通过多对多关系连接的订单和产品

我正在尝试获取所有订单以及相关产品,如下所示:

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

我的订单模型设置为

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

当我输出日志时,我收到以下错误消息:

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

问题是 Laravel 正在 Pivot 中寻找一个名为“order_order_id”的表,该表不存在。我还没有声明要调用的列。我的数据透视表列称为“order_id”和“product_id

我不知道 Laravel 如何假定数据透视表名称。有没有办法专门声明数据透视表中的列名?还是我在命名约定中犯了错误?

【问题讨论】:

    标签: php mysql laravel eloquent


    【解决方案1】:

    如果您有两个名为 OrderProduct 的模型,并且它们与它们的数据库表之间存在许多关系,例如 ordersproducts,那么 Laravel 将搜索一个名为 order_product 的数据透视表(模型名称以字母顺序排列)顺序并由 '_' 加入)。
    order_product 表将由两列 order_id,product_id 组成。简而言之,这是数据透视表的基本命名约定 :)。

    【讨论】:

      【解决方案2】:

      编辑 Order 模型并尝试以下代码:

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2019-10-20
        • 2018-01-10
        • 2014-03-17
        • 1970-01-01
        • 2013-06-04
        • 1970-01-01
        • 1970-01-01
        • 2014-07-18
        相关资源
        最近更新 更多