在我的网站上,我有一个项目表,与另一个表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();
答案 0 :(得分:0)
我认为你的关系是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();