Chris
Chris

Reputation: 58312

How to use the `where` method along with the `with` method in laravel 4?

Given the following, very simple, example:

Country Class

class Country extends Eloquent {
    protected $table = "countries";
    protected $fillable = array(
        'id',           
        'name'
    );

    public function state() {
        return $this->hasMany('State', 'country_id');
    }   
}

State Class

class State extends Eloquent {
    protected $table = "states";
    protected $fillable = array(
        'id',           
        'name',
        'country_id' #foreign
    );

    public function country() {
        return $this->belongsTo('Country', 'country_id');
    }
}

How can I list all the states, based on the id or the name of the country.

Example:

State::with('country')->where('country.id', '=', 1)->get()

The above returns an area, as country is not part of the query (Eloquent must attach the join later, after the where clause).

Upvotes: 2

Views: 409

Answers (1)

Lance Pioch
Lance Pioch

Reputation: 1167

I think you're either misunderstanding the relations or over-complicating this.

class Country extends Eloquent {
    public function states() {
        return $this->hasMany('State', 'state_id');
    }   
}

$country = Country::find(1);
$states = $country->states()->get();

Upvotes: 3

Related Questions