2

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?

0

3 Answers 3

6

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.

Sign up to request clarification or add additional context in comments.

Comments

0

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']);
}

1 Comment

for second solution ok, but for first solution. Not working form me. It return null on field "user_detail" in model.
0
$result = Staff::where('live_status',2)
            ->with('position')->with('department')->with('gender')
            ->with(['partner' => function($query){
                    $query->where('alive',0);
                }]);

1 Comment

Add explanation please.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.