Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel 5 Eloquent scope join and select specific columns

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.

like image 518
bakamike Avatar asked Mar 06 '15 22:03

bakamike


People also ask

How do I select a specific column in Laravel?

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.

What is difference between Pluck and select in Laravel?

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.

How do you join two tables with an eloquent relationship?

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.


1 Answers

You may try this:

->select('accounts.*', 'users.id as uid','users.user_name');
like image 190
The Alpha Avatar answered Sep 17 '22 15:09

The Alpha