2014-11-24 134 views
0

結果在我的網站,我有一個項目表,並具有許多與另一臺project_user一對多的關係,Laravel和雄辯返回從一個多對多的關係

在工作表中我將有一排看起來是這樣的,

| ID | NAME  | 
|-----|-------------| 
| 1 | Project 1 | 

在project_user表我有一些行看起來像這樣,

| ID | PROJET_ID | USER_ID | 
|-----|-------------|---------| 
| 1 |  1  | 2 | 
| 1 |  1  | 4 | 
| 1 |  1  | 10 | 

項目模型看起來是這樣的,

class Project extends Eloquent { 

    protected $fillable = [ 
     'name', 
     'description', 
     'total_cost', 
     'start_date', 
     'finish_date', 
     'sales_person', 
     'project_manager', 
     'client_id', 
     'organisation_id', 
     'user_id' 
    ]; 

    public function collaborators() { 
     return $this->belongsToMany('User'); 
    } 
} 

和用戶表中的模型看起來像這樣,

class User extends Eloquent implements UserInterface, RemindableInterface { 

    use UserTrait, RemindableTrait; 

    /** 
    * The database table used by the model. 
    * 
    * @var string 
    */ 
    protected $table = 'users'; 

    /** 
    * The attributes excluded from the model's JSON form. 
    * 
    * @var array 
    */ 
    protected $hidden = array('password', 'remember_token'); 

    public function users() 
    { 
     return $this->belongsToMany('Project'); 
    } 
} 

我想知道的是我怎麼能與用戶信息一起從數據庫中獲取一個項目,它的相關用戶怎麼辦?我目前正在此,

$project = Project::whereHas('user', function($q) 
     { 
      //$q->where('user_id', '=', ResourceServer::getOwnerId()); 

     })->get(); 

回答

0

我認爲你們的關係是projectusers,所以這是非常簡單的:如果你想只有一個項目

$user->load('projects.users'); 

$user->projects; // collection of user's projects 

$user->projects->first()->collaborators; // collection of users in signle project 

,那麼你可以做:

$user->projects()->find($projectId)->collaborators; 

您嘗試的方式也可以使用:

Project::whereHas('collaborators', function ($q) { 
    $q->where(..); 
})->with('collaborators')->get();