Laravel - joining 3 tables
Clash Royale CLAN TAG#URR8PPP
Laravel - joining 3 tables
I have 3 tables: users, visits, bloodtests
The Tables look like this:
users: id
visits: id, user_id
bloodtests: id, visit_id
What I need to get is "SELECT * FROM bloodtests" for the current user
I tried this way:
$item = User::findOrFail($id); //get ID of current user
$bt = DB::table('bloodtests')
->join('visits', 'bloodtests.visit_id', '=' ,'visits.id')
->join('users', 'visits.user_id', '=' ,'users.id')
->select(
'bloodtests.id',
'bloodtests.visit_id')
->where('users.id', $item)
->get();
But it doesnt work.
Any help is appreciated :)
the query returns nothing (should return 2 records - based on data in my DBs)
– piotr.jowisz
Aug 5 at 17:32
you can use
toSql()
method to check your sql– Sakezzz
Aug 5 at 17:38
toSql()
3 Answers
3
Try this:
$item = User::findOrFail($id);
$bt = DB::table('bloodtests')
->join('visits', 'bloodtests.visit_id', '=' ,'visits.id')
->join('users', 'visits.user_id', '=' ,'users.id')
->select(
'bloodtests.id',
'bloodtests.visit_id')
->where('users.id', $item->id)
->get();
You are getting all users data as collection with this
$item = User::findOrFail($id);
You just need to provide current user's id by Auth::id()
or direct using $id
instead $item
Auth::id()
$id
$item
$bt = DB::table('bloodtests')
->join('visits', 'bloodtests.visit_id', '=' ,'visits.id')
->join('users', 'visits.user_id', '=' ,'users.id')
->select(
'bloodtests.id',
'bloodtests.visit_id')
->where('users.id', Auth::id())
->get();
or direct using $id
$id
->where('users.id', $id)
$item = User::findOrFail($id); //get ID of current user
$bt = DB::table('bloodtests')
->join('visits', 'bloodtests.visit_id', '=' ,'visits.id')
->join('users', 'visits.user_id', '=' ,'users.id')
->select(
'bloodtests.id',
'bloodtests.visit_id')
->where('users.id', $id)
->get();
By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.
what kind of error does it shows? It is unclear.
– Sakezzz
Aug 5 at 17:22