[英]Laravel and eloquent returning results from a many to many relationship
在我的網站上,我有一個項目表,並且該表與另一個表project_user有很多關系,
在項目表中,我會有一行像這樣,
| 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();
我想你的關系是project
而不是users
,所以很簡單:
$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();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.