2

有没有办法在 eloquent 中使用“with”时只选择特定的列?

我的问题是我得到了一个很长的帐户列表,我还需要使用关系“with”来获取他们的网站,但是“websites”对象很大,它使请求非常慢。

我尝试使用:

$accounts = $accounts->with('websites')->select(['account_id','url']);

并且:

$accounts = $accounts->with('websites', function($query) {
                $query->select(['account_id','url']);
            });

他们都没有工作。

我在他们的文档中没有看到这个答案,所以如果有一种方法,如果有人愿意与我分享,我将不胜感激。此外,如果“with”有一个替代方案可以给出相同的结果,那也很好。谢谢。

4

2 回答 2

8
$accounts = $accounts->with([
    'websites'  => function($query) {
        $query->select(['account_id','url']);
    }
]);
于 2016-06-23T07:34:11.170 回答
2

尝试定义关系中的列:

class Account
{
    public function websites()
    {
        return $this->hasMany('App\Website')->select(['account_id','url']);
    }
}

请注意,类和关系仅用于演示目的,请尝试将其添加->select(['account_id','url'])到您的关系中。

于 2016-06-23T07:30:59.167 回答