Toskan
Toskan

Reputation: 14961

eloquent use ->with() with only retrieving one column?

e.g.

i want to retrieve all users with the relation roles, but only the field of role name.

something like this:

User::with('user_role', 'user_role.name')

does something like this exist? i have looked around and don't seem to find something related. The performance might be better if you can filter down the returned columns

Upvotes: 0

Views: 391

Answers (2)

The Alpha
The Alpha

Reputation: 146269

Yes, you can use something like this:

$user = User::with('user_role:foreign_key,name')->find(1);

In this case, the foreign_key should be the name of the foreign key that is used to build the relation and it's required here and then you may pass other field names to select them by separating with comma.

This is not documented so be careful, it could be removed in the newer versions. It exists there and below is the code sample, taken from Laravel-5.3 (Illuminate\Database\Eloquent\Builder), it works tho (This is how I've used it: User::with('messages:recipient_id,body')->get()):

/**
 * Parse a list of relations into individuals.
 *
 * @param  array  $relations
 * @return array
 */
protected function parseWithRelations(array $relations)
{
    $results = [];

    foreach ($relations as $name => $constraints) {
        // If the "relation" value is actually a numeric key, we can assume that no
        // constraints have been specified for the eager load and we'll just put
        // an empty Closure with the loader so that we can treat all the same.
        if (is_numeric($name)) {
            if (Str::contains($constraints, ':')) {
                list($constraints, $columns) = explode(':', $constraints);

                $f = function ($q) use ($columns) {
                    $q->select(explode(',', $columns));
                };
            } else {
                $f = function () {
                    //
                };
            }

            list($name, $constraints) = [$constraints, $f];
        }

        // We need to separate out any nested includes. Which allows the developers
        // to load deep relationships using "dots" without stating each level of
        // the relationship with its own key in the array of eager load names.
        $results = $this->parseNestedWith($name, $results);

        $results[$name] = $constraints;
    }

    return $results;
}

Upvotes: 2

jfadich
jfadich

Reputation: 6348

You can add constraints to eager loaded relations by supplying a with array with closure as the value with the relation as the key.

$user = User::with(['user_role' => function($query) {
    return $query->select('name');
}]);

Upvotes: 1

Related Questions