LorenzoBerti
LorenzoBerti

Reputation: 6974

Laravel 5.1 select field in with function

Can I select value from relationships with function "with" ? So make something like this:

$test = User::where('id',1)->with(['user_detail' => function($query){
            $query->select("detail_1");
        }])->get();

Yes I know that I can put select in relation "user_detail" but can I select in with function?

Upvotes: 2

Views: 6470

Answers (3)

user10984023
user10984023

Reputation: 1

$result = Staff::where('live_status',2)
            ->with('position')->with('department')->with('gender')
            ->with(['partner' => function($query){
                    $query->where('alive',0);
                }]);

Upvotes: 0

The Alpha
The Alpha

Reputation: 146191

You can select within with as you made the example given below:

$test = User::where('id',1)->with(['user_detail' => function($query){
    $query->select("detail_1");
}])->get();

But it won't not work (as you commented in other answer) because you've only selected a single property but the foreign key is not available in your select statement. So, make sure that, you also select the related foreign key as well and then it'll work.

In your case, I believe that, you've to also select the user_id in your select for example:

$test = User::where('id',1)->with(['user_detail' => function($query){
    $query->select(
        'user_id', // This is required if this key is the foreign key
        'detail_1'
    );
}])->get();

So, without the foreign key that makes the relation, Eloquent won't be able to load the related models and that's why you get null in your result as you mentioned in other comment.

Upvotes: 6

Alexey Mezenin
Alexey Mezenin

Reputation: 163748

Yes, you can use select() inside with(). Just pass an array of columns:

$query->select(['detail_1', 'detail_2']);

Alternatively, you can create another relation and add select() to it:

public function userDatails()
{
    return $this->hasMany('App\UserDetail')->select(['detail_1', 'detail_2']);
}

Upvotes: 0

Related Questions