Laravel 5.2在热切加载的查询中雄辩使用Select

时间:2016-04-08 06:47:01

标签: laravel laravel-5 laravel-5.2

我可以使用select:

来解决这个问题
User::whereNotIn('id', $ids)
    ->select(['id', 'email'])
    ->with('profile')
    ->get();

我只想在急切加载的用户个人资料中检索几个密钥。我想做这样的事情:

User::whereNotIn('id', $ids)
    ->select(['id', 'email'])
    ->with(['profile', function ($query) {
        $query->select(['id', 'user_id', 'first_name', 'last_name']);
    }])->get();

或者:

User::whereNotIn('id', $ids)
    ->select(['id', 'email'])
    ->with(['profile', function ($query) {
        $query->addSelect(['id', 'user_id', 'first_name', 'last_name']);
    }])->get();

但这似乎不起作用,我收到了这个错误:

ErrorException in Builder.php line 1034:
explode() expects parameter 2 to be string, object given

在/Illuminate/Database/Eloquent/Builder.php中抛出:

/**
 * Parse the nested relationships in a relation.
 *
 * @param  string  $name
 * @param  array   $results
 * @return array
 */
protected function parseNestedWith($name, $results)
{
    $progress = [];

    // If the relation has already been set on the result array, we will not set it
    // again, since that would override any constraints that were already placed
    // on the relationships. We will only set the ones that are not specified.
    foreach (explode('.', $name) as $segment) { // <--- line 1034
        $progress[] = $segment;

        if (! isset($results[$last = implode('.', $progress)])) {
            $results[$last] = function () {
                //
            };
        }
    }

    return $results;
}

有没有办法实现这个目标?

1 个答案:

答案 0 :(得分:2)

在预先加载约束闭包

中使用“addSelect”而不是“select”
User::whereNotIn('id', $ids)->select(['id', 'email'])
    ->with(['profile' => function($query) {
        $query->addSelect(['id', 'user_id', 'first_name', 'last_name']);
    }])->get();

您必须在addSelect中包含外键,否则将不会加载任何内容