Reputation: 107
I have two tables available. 1) Users 2) Friendships. Following is the table structure:
Now I want to retrieve data from the "users" table using the "sender_id," which is the same as the "id" in the "users" table.
I'm using the left join to perform the required query as follow:
public function show_friend_request(){
$user_id = auth()->user()->id;
**//Below query will get the userID's of people who have sent the request to current user.**
$get_friend_requests = DB::table('friendships')->where('recipient_id',$user_id)
->where('status','pending')->get(['sender_id'])->first()->sender_id;
$show_friend_request_Data = DB::table('users')
->leftJoin('friendships', 'sender_id', '=', $get_friend_requests)
->get();
return $show_friend_request_Data ;
}
But when i executed the above code i'm getting the following error:
Illuminate \ Database \ QueryException
SQLSTATE[42S22]: Column not found: 1054 Unknown column 'users.sender_id' in 'on clause'
select * from `users` left join `friendships` on `users`.`sender_id` = `63b8760f-826b-4c1c-aea9-23f1dff148db`
Upvotes: 0
Views: 774
Reputation: 2746
All you have to do is:
$show_friend_request_Data = DB::table('users')
->leftJoin('friendships', 'friendships.sender_id', '=', 'users.id')
->where('users.id', '=', $get_friend_requests)
->get();
I also suggest you to think of how to optimise the whole query to only 1 request and also how to get multiple friend requests at the time. Because now you're only getting the first friend pending friend request ;)
Upvotes: 1