lundi 3 juillet 2017

Laravel DB query joining multiple tables and fetching conditional data

I have the following list of tables that I want to query data from

users 
id email   
1 user1@test.com
2 user2@test.com          

user_projects 
project_id user_id role               
1           1       member
1           2       owner

projects 
id name 
1  example project

I want the resultant data to look like the following

project_id name              email             role    owner
1          example project   user1@test.com    member  user2@test.com

In short, I would like to fetch the list of projects the user is a part of along with his role and the owner of the project.

I came up with the following query

return DB::table('user_projects')
        ->join('projects', 'user_projects.project_id', '=', 'projects.id')
        ->join('users', 'user_projects.user_id', '=', 'users.id')
        ->where('user_projects.user_id', '=', $userId)
        ->select('users.email', 'projects.id', 'users.id as user_id','user_projects.role as userRole',
            'projects.name')
        ->get()->toArray();

I am able to get the list of projects and the user's role in the project but unable to find the email owner of the project.



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire