如何从Laravel Eloquent中的多个父对象中选择链接对象

时间:2013-07-06 18:05:57

标签: laravel laravel-4

我想做这样的事情。

Location::where('city', '=', 'Chicago')->chef();

有了这些关系:

class Location extends Eloquent {
    protected $table = 'locations';

    public function chef() {
        return $this->belongsTo('Chef');
    }
}

class Chef extends Eloquent {
    protected $table = 'chefs';

    public function location() {
        return $this->hasMany('Location');
    }
}

1 个答案:

答案 0 :(得分:2)

这应该有效:

class Location extends Eloquent {
    protected $table = 'locations';

    public function chefs() {
        return $this->belongsTo('Chef');
    }

    public function getAllChefsByCity($city)
    {
         $this->with('chefs')->where('city', $city)->get();
    }
}

然后在你的代码中:

$array = $location->getAllChefsByCity('Chicago');