MD. Atiqur Rahman
MD. Atiqur Rahman

Reputation: 2173

Laravel Table Joining

I have three tables .

users

id name

roles

id name

role_user

id user_id role_id

I want to join them like

id name name(role) user_id role_id

My vision is to show the role name of the user.

I have tried this :

DB::table('users')
            ->join('role_user', 'users.id', '=', 'role_user.user_id')
            ->join('roles', 'role_user.role_id', '=', 'roles.id')
            ->select('users.id', 'role_user.role_id', 'roles.name')
            ->get();

Can you please tell me what I am doing wrong or if I am going thru a bad way.

Thanks in Advance

Upvotes: 0

Views: 63

Answers (1)

user6284414
user6284414

Reputation:

The name field is "double". This is not a problem for your database but it will not display well. Try the following code:

$result = DB::table('..etc.')->get(['users.*','role_user.role_id','roles.name as role_name']);
foreach($result as $row) {
    print_r($row->toArray());
}

As you can see I've changed the get() call to make sure that the user's "name" field does not clash with the role's "name" field.

Upvotes: 0

Related Questions