Laravel Eloquent查询枢轴表不是唯一的

时间:2016-01-17 19:35:07

标签: laravel eloquent

由于某些原因,我在执行以下操作时无法获得预期结果:

$cars = Car::query();
$cars->whereIsVisible(true);

# output: $list 
// [2016-01-16 09:30:04] local.INFO: array (
//   0 => 5,
//   1 => 7,
//   2 => 9,
//   3 => 3,
// )  

$cars->whereHas('specifications', function($query) use ($list) {
    $query->whereIn('id', ($list)); 
});

$cars->get();

我的期望是,我只获得了具有$ list内所有规格的汽车,但这不正确。即使我填写更多规格,我也会得到更大的结果。所以出了点问题。

我以前是Eloquent,所以我很讨厌。但这是查询:

select * from "cars" where "cars"."deleted_at" is null 
and "is_visible" = true 
and (select count(*) 
from "specs" inner join "car_specs" 
on "specs"."id" = "car_specs"."facility_id" 
where "car_specs"."car_id" = "cars"."id" 
and "id" in (5, 7, 9 ,3)) >= 1 

有人知道哪里出错了吗?以及如何解决它?

1 个答案:

答案 0 :(得分:0)

根据https://laravel.com/docs/5.1/eloquent-relationships#querying-relations

whereHas只是检查您是否拥有提供规格的汽车,而不是返回符合您规格的汽车。

我认为你应该直接使用where

相关问题