To get join results as an array of objects in Laravel, you can use the get
method after performing the join.
Here’s an example of how you can perform a JOIN
using the DB
class:
1 2 3 4 5 6 7 8 9 |
$users = DB::table('users') ->join('orders', 'users.id', '=', 'orders.user_id') ->get(); foreach ($users as $user) { echo $user->name; } |
This will execute a JOIN
between the users
and orders
tables on the user_id
column, and return the results as an array of objects.
You can also use the select
method to specify which columns to select, and the where
method to specify a condition for the query.
1 2 3 4 5 6 7 |
$users = DB::table('users') ->join('orders', 'users.id', '=', 'orders.user_id') ->select('users.name', 'orders.total') ->where('orders.total', '>', 1000) ->get(); |
Here’s an example of how you can perform a JOIN
using Eloquent ORM:
1 2 3 4 5 6 7 8 9 10 11 |
use App\User; use App\Order; $users = User::join('orders', 'users.id', '=', 'orders.user_id') ->get(); foreach ($users as $user) { echo $user->name; } |
This will execute a JOIN
between the users
and orders
tables on the user_id
column, and return the results as an array of User
objects.
You can also use the select
method to specify which columns to select, and the where
method to specify a condition for the query.
1 2 3 4 5 6 |
$users = User::join('orders', 'users.id', '=', 'orders.user_id') ->select('users.name', 'orders.total') ->where('orders.total', '>', 1000) ->get(); |