我在Laravel的这种多对多关系中遇到了困难。我有多对多的关系,项目和人。我还有第三个表,角色(有2列:id,name),其中包含一个人可以在项目中拥有的角色(在这种情况下,“演员”,“导演”等)。数据透视表person_project具有列“person_id”,“project_id”和“role_id”。我成功地使用
获得了与项目相关的所有人员$project = Project::find($id);
$project->persons;
但是,我怎样才能让在项目中扮演特定角色的人?我将如何挽救这种关系呢?
型号:
// Project.php
class Project extends Eloquent {
protected $table = 'projects';
public $timestamps = false;
public function persons() {
return $this->belongsToMany('Person');
}
}
// Person.php
class Person extends Eloquent {
protected $table = 'persons';
public $timestamps = false;
public function projects() {
return $this->belongsToMany('Project');
}
}
答案 0 :(得分:1)
This article有助于弄清楚检索关系。 Eloquent的withPivot()和join()方法是让它发挥作用的关键。
// In the Project model
public function persons() {
return $this->belongsToMany('Person')
->withPivot('role_id')
->join('roles', 'role_id', '=', 'roles.id');
}
我找到了Laravel文档中的插入部分:http://laravel.com/docs/eloquent#inserting-related-models 在此示例中,Input :: get('directors')是一个person_ids数组,选择连接到“director”角色。对于Input :: get('actors')也是如此。
// Within the update method of the Projects controller
foreach (Input::get('directors') as $directorId) {
$project->persons()->attach($directorId, array('role_id' => 1)); // roles.id 1 = "director"
}
foreach (Input::get('actors') as $actorId) {
$project->persons()->attach($actorId, array('role_id' => 2)); // roles.id 2 = "actor"
}
答案 1 :(得分:0)
请尝试以下方法之一:
如果您使用 Laravel 4.1 :
$project = Project::whereHas('persons', function($q)
{
$q->where('role_id', 1);
})->get();
Laravel 4和4.1:
$project = Project::with(array('persons' => function($query)
{
$query->where('role_id', 1);
}))->get();