如何限制Laravel中多对多关系的急切加载?

时间:2013-12-30 01:24:11

标签: php mysql laravel-4

RE,

我有一个典型的多对多关系设置如下:

class Feature extends Eloquent  {

    public function cars()
    {
        return $this->belongsToMany('Car', 'car_feature', 'feature_id', 'car_id');
    }
}

class Car extends Eloquent  {

    public function features()
    {
        return $this->belongsToMany('Feature', 'car_feature', 'car_id', 'feature_id');
    }
}

我试图找到所有具有功能的汽车(有些没有)并急切地加载模型:

$cars = Car::with(array('features' => function($query)
{
   $query->where("title", "leather");
}))->get();

foreach ($cars as $car) {
    return $car;
}

它执行2个查询:

SELECT * from `cars`;

SELECT `features`.*, `car_feature`.`car_id` as `pivot_car_id`, `car_feature`.`feature_id` as `pivot_feature_id` 
    FROM `features` 
    INNER JOIN `car_feature` on `features`.`id` = `car_feature`.`feature_id` 
    WHERE `car_feature`.`car_id` in (1, 2, ..., 9000) and `title` = 'leather';

查询没问题,如果我在SQL中运行第二个查询,它会生成我想要的结果。然而,通过退回的物品,它输出所有汽车而不是具有“皮革”作为特征的汽车。是什么给了什么?

感谢。

谢谢!

1 个答案:

答案 0 :(得分:5)

如果您使用的是Laravel 4.1,则可以使用whereHas方法,如下所示(未经测试):

$cars = Car::whereHas('features', function($query)
{
   $query->where("title", "leather");
})->get();