如何在“ With”(ManyToMany Laravel)中制作where-filter?

时间:2018-12-29 08:35:33

标签: laravel-5.2

与多对多的关系。 我正在尝试发出请求:

$products=Product::with(['lists' => function($query)
                {
           $query->where('user_id', Auth::id());
                }])
                ->orderBy('id', 'desc')
                ->paginate(20);

但是我得到一个错误。

"SQLSTATE[23000]: Integrity constraint violation: 1052 Column 'user_id' in where clause is ambiguous (SQL: select `mainlists`.*, `list_products`.`product_id` as `pivot_product_id`, `list_products`.`list_id` as `pivot_list_id` from `mainlists` inner join `list_products` on `mainlists`.`id` = `list_products`.`list_id` where `user_id` = 16 and `list_products`.`product_id` in (73, 80, 81, 87, 88, 89)

这些关系在各种其他查询中也能正常工作。 我认为我的请求对于ManyToMany关系类型是错误的。 因为查询正在尝试将多个产品与数据透视表进行比较。

1 个答案:

答案 0 :(得分:0)

因为您的productlist都拥有user_id 您应该选择要考虑的user_id

像这样:

$products=Product::with(['lists' => function($query)
            {
       $query->where('list_products.user_id', Auth::id());
            }])
            ->orderBy('id', 'desc')
            ->paginate(20);
相关问题