雄辩使用 - > with()仅检索一列?

时间:2017-04-19 22:28:15

标签: laravel eloquent laravel-5.3

e.g。

我想检索具有关系角色的所有用户,但只检索角色名称字段。

类似的东西:

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

这样的事情存在吗?我环顾四周,似乎找不到相关的东西。如果您可以过滤掉返回的列

,性能可能会更好

2 个答案:

答案 0 :(得分:2)

是的,您可以使用以下内容:

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

在这种情况下,foreign_key应该是用于构建关系的外键的名称,这是必需的,然后您可以传递其他字段名称,通过用逗号分隔来选择它们。

这没有记录,所以要小心,它可以在较新的版本中删除。它存在于下面,代码示例取自Laravel-5.3(Illuminate \ Database \ Eloquent \ Builder),它的工作原理(这就是我使用它的方式: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;
}

答案 1 :(得分:1)

您可以通过提供一个带有闭包的with数组作为以关系为键的值来为急切加载的关系添加约束。

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