【问题标题】:Laravel Eloquent querying pivot table not uniqueLaravel Eloquent 查询数据透视表不是唯一的
【发布时间】:2016-01-18 05:06:25
【问题描述】:

由于某种原因,我在执行以下操作时没有得到预期的结果:

$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 

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

【问题讨论】:

    标签: laravel eloquent


    【解决方案1】:

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

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

    我认为你应该直接使用where

    【讨论】:

      猜你喜欢
      • 2018-11-11
      • 2015-06-24
      • 2015-09-30
      • 2016-12-06
      • 1970-01-01
      • 2022-06-11
      • 2015-12-28
      • 1970-01-01
      相关资源
      最近更新 更多