简体   繁体   中英

How to constraint eager loading of many-to-many relationship in Laravel?

Re,

I have a typical many-to-many relationship set up as follows:

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');
    }
}

I am trying to find ALL cars that have features (some don't) and eager load the model:

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

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

It executes 2 queries:

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';

The query is OK and if I run the second one in SQL, it produces the results that I want. However, going through the returned items, it outputs ALL cars and not the ones with "leather" as a feature. What gives?

Thanks.

Thanks!

Provided you're using Laravel 4.1, you can use the whereHas method, something like the following (untested):

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM