Laravel 5 Eloquent scope连接并选择特定列

bak*_*ike 10 scope laravel eloquent

我有一个Eloquent模型,在模型中我使用范围查询来进行连接.这一切都工作正常,但我试图弄清楚在范围查询中如何只从连接表中选择某些列.

这是我的控制器中的方法.

$accounts = Account::creator()->get();
Run Code Online (Sandbox Code Playgroud)

这是模型中的范围查询

public function scopeCreator($query) {
        $query->leftJoin('users','users.id','=','accounts.creator_id');
}
Run Code Online (Sandbox Code Playgroud)

这有效,但它返回帐户和用户的所有列,但我只想要帐户中的所有列,而只需要用户的2列.

我试过这个......

public function scopeCreator($query) {
        $query->leftJoin('users','users.id','=','accounts.creator_id')->select(array('id','user_name'));
}
Run Code Online (Sandbox Code Playgroud)

但是,这仅返回用户的那两个字段,并忽略帐户中的列.我知道如何用2种不同的模型做到这一点,但这意味着我必须创建一个无用的模型.这个范围查询功能非常棒,如果我能搞清楚这一部分的话.

The*_*pha 17

你可以试试这个:

->select('accounts.*', 'users.id as uid','users.user_name');
Run Code Online (Sandbox Code Playgroud)