I have an Eloquent model and in the model I am using a scope query to do a join. This all works fine but I am trying to figure out how in the scope query to select only certain columns from the joined table.
Here is the method in my controller.
$accounts = Account::creator()->get();
Here is the scope query in the model
public function scopeCreator($query) {
$query->leftJoin('users','users.id','=','accounts.creator_id');
}
This works but it returns all the columns from accounts and users but I only want all the columns from accounts and only 2 columns from users.
I tried this...
public function scopeCreator($query) {
$query->leftJoin('users','users.id','=','accounts.creator_id')->select(array('id','user_name'));
}
However this returns only those 2 fields from users and ignores the columns from accounts. I know how to do this with 2 different models but that means I have to create a useless model. This scope query functionality is great if I can just get this part figured out.
Select specific columns with Laravel Eloquent To get all of the columns from the users table, we would use the following: $user = User::where('username', 'bobbyiliev')->get(); However, if you wanted to get only a specific column, you could pass it as an argument to the get() method.
Pluck function normally used to pull a single column from the collection or with 2 columns as key, value pairs, which is always be a single dimension array. Select will return all of the columns you specified for an entity in a 2 dimensional array, like array of selected values in an array.
If you want to join two or multiple tables in laravel then you can use laravel eloquent join(), left join(), right join(), cross join(). And another option to join two or multiple table, you can use laravel eloquent relationships instead of laravel join.
You may try this:
->select('accounts.*', 'users.id as uid','users.user_name');
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With