Laravel 5 Eloquent 范围连接并选择特定列

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/28908475/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 11:05:02  来源:igfitidea点击:

Laravel 5 Eloquent scope join and select specific columns

laravelscopeeloquent

提问by bakamike

I have an Eloquent model and in the model I am using a scope query to do a join. This all works fine but I am trying to figure out how in the scope query to select only certain columns from the joined table.

我有一个 Eloquent 模型,在模型中我使用范围查询进行连接。这一切都很好,但我想弄清楚如何在范围查询中只从连接表中选择某些列。

Here is the method in my controller.

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

$accounts = Account::creator()->get();

Here is the scope query in the model

这是模型中的范围查询

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

This works but it returns allthe columns from accounts and users but I only want all the columns from accounts and only 2 columns from users.

这有效,但它返回来自帐户和用户的所有列,但我只想要来自帐户的所有列和来自用户的仅 2 列。

I tried this...

我试过这个...

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

However this returns only those 2 fields from users and ignores the columns from accounts. I know how to do this with 2 different models but that means I have to create a useless model. This scope query functionality is great if I can just get this part figured out.

但是,这仅从用户返回这 2 个字段,并忽略帐户中的列。我知道如何用 2 个不同的模型来做到这一点,但这意味着我必须创建一个无用的模型。如果我能弄清楚这部分,这个范围查询功能就很棒。

回答by The Alpha

You may try this:

你可以试试这个:

->select('accounts.*', 'users.id as uid','users.user_name');