Matthijn
Matthijn

Reputation: 3234

Laravel limit with (not globally)

I have the following query I want to execute with Eloquent.

$restaurant = Restaurant::with([
    'user' => function($query)
    {
        $query->select(['username']); // This doesn't work
        $query->whereStatus('confirmed');
    }
])->find($id);

I want to fetch a Restaurant and it's corresponding User (they are related) but from the User I don't wan't all the information. Only the username in this case.

I could add a property $hidden to the User model, but then they would be hidden for every query (in array / json form). But I only want to limit it a bit more for this query.

If I add the select (with or without wrapping it in an array) I get the following result:

{
    'id': 1,
    'user': null
}

Yet if I remove that select I get the full User:

{
    'id': 1,
    'user': { .. json user data }
}

The User does exist and the username is not empty. How can I go about this?

Here the actual output can be found.

Edit: When I change the value in the select to something that does not exist in the database I see an error, and from that I deduct that the Query is correct, but I just don't get any output. (Query I get when using an invalid column 'test').

select `test` from `users` where `users`.`deleted_at` is null and `users`.`userable_id` in (1) and `users`.`userable_type` = Restaurant and `status` = confirmed)

Upvotes: 0

Views: 217

Answers (1)

Marcin Nabiałek
Marcin Nabiałek

Reputation: 111839

Try this way:

$restaurant = Restaurant::with([
    'user' => function($query)
    {
        $query->whereStatus('confirmed')->lists('username');
    }
])->find($id);

EDIT

It seems that both methods will work but you need to fulfil one condition - you need to include foreign_key column in the lists/select. I don't know what is your relation but for example assuming you have in users table restaurant_id column you would need to use the following code:

$restaurant = Restaurant::with([
    'user' => function($query)
    {
        $query->select(['username', 'restaurant_id'])->whereStatus('confirmed');
    }
])->find($id);

or

$restaurant = Restaurant::with([
    'user' => function($query)
    {
        $query->whereStatus('confirmed')->lists('username','restaurant_id');
    }
])->find($id);

I don't know if it is possible for n:n relationship. You should also consider that this might be a bit dangerous (some problems may occur) so you should play with it only if you have strong reason just to grab selected columns.

Upvotes: 1

Related Questions