简体   繁体   English

Laravel和多对多关系雄辩地返回结果

[英]Laravel and eloquent returning results from a many to many relationship

In my website, I have a project table and that has a many to many relationship with another table project_user, 在我的网站上,我有一个项目表,并且该表与另一个表project_user有很多关系,

In the project table I would have a row that looks like this, 在项目表中,我会有一行像这样,

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

In the project_user table I have some rows that look like this, 在project_user表中,我有些行看起来像这样,

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

The project model looks like this, 项目模型如下所示:

    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');
    }
}

And the model for the user table looks like this, 用户表的模型如下所示,

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');
    }
}

What I want to know is how can I get a project from the database along with the user details for it's relevant users? 我想知道的是如何从数据库中获取项目以及相关用户的用户详细信息? I am currently trying this, 我目前正在尝试

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

        })->get();

I suppose your relation is project not users , so it's pretty straightforward: 我想你的关系是project而不是users ,所以很简单:

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

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

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

If you want only one project, then you can do: 如果只需要一个项目,则可以执行以下操作:

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

The way you tried will also work: 您尝试过的方式也可以:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM