Search code examples
laravelconstraintseager-loadingbelongs-to

Laravel 4 Eager Load Constraints with BelongsTo


I have two Models... Aircraft and Movement:

In Aircraft:

public function movements() {
    return $this->hasMany('Movement');
}

In Movement:

public function aircraft() {
    return $this->belongsTo('Aircraft');
}

Table Movement:

Schema::create('movements', function($table)
    {
        $table->increments('id');
        $table->boolean('flag_visible')->default(1);
        $table->integer('aircraft_id')->nullable()->default(NULL);
        $table->timestamps();
    });

Table Aircraft:

Schema::create('aircrafts', function($table)
    {
        $table->increments('id');
        $table->string('identifier');
        $table->timestamps();
    });

Now I want select all movements with Aircrafts with identifiers = 10:

$movements = Movement::with(array(
            'aircraft' => function($query) {
                $query->where('identifier', 'like', '%10%');
            }
        ));

I Have only ONE movement record with an aircraft_id where the Identifier is %10%. But I get ALL movements records, only the one with the right identifier has the relationship "aircraft". But I want an array only with ONE record, only the one with the right identifier.. what is wrong here?


Solution

  • with() creates a separate query to retrieve all the related values at once (eager loading) instead of as-needed (lazy loading).

    You're looking to add a constraint on the movement query, so you should use whereHas(), something like this:

    $movements = Movement::whereHas('aircraft', function($q)
    {
        $q->where('identifier', 'like', '%10%');
    
    })->get();