'Laravel Query Builder Joins
Good afternoon pips, I would like to ask for your help.
Could you please help me apply this query into the Laravel Query Builder. I only know how to query into the database using raw query.
Query:
SELECT users.first_name, users.last_name, users.id as userID, bookmarks.id,
products.title, products.price, products.id AS productID FROM users,
products, bookmarks WHERE bookmarks.user_id = $user_id AND products.id =
bookmarks.product_id AND users.id = products.user_id;
Thank you for those people that would help me.
Solution 1:[1]
$result = DB::select(DB::raw('custom_query'));
$user_name = $result[0]->first_name.' '.$result[0]->last_name;
Solution 2:[2]
SELECT users.first_name, users.last_name, users.id as userID, bookmarks.id, products.title, products.price, products.id AS productID FROM users, products, bookmarks WHERE bookmarks.user_id = $user_id AND products.id = bookmarks.product_id AND users.id = products.user_id;
You can use the eloquent with method and just access the relations but if you want the laravel query method. You can use the DB::raw to have your own raw query.
DB::select(DB::raw("Select a.first_name, a.last_name, a.id as user_id, b.id, c.title, c.price, c.id from users as a INNER JOIN bookmarks as b on b.user_id = $user_id INNER JOIN Products as c on c.id = b.product_id where user_id = c.user_id"));
This is just an example, it's still up to you on how you manipulate your queries.
Love, Poop
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | swaroop suthar |
| Solution 2 | Valerie Bantilan |
