简体   繁体   中英

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,

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,

| 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:

$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();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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