Laravel eloquent - 在加入表时防止覆盖值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/24018304/
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 09:35:58  来源:igfitidea点击:

Laravel eloquent - prevent overriding values when joining tables

phpjoinlaraveleloquent

提问by plunntic iam

Ok, so i have following two models: Accountand Role

好的,所以我有以下两个模型:AccountRole

class Account extends Eloquent
{
  protected $table = 'account';

  /* [...] */

  public function group() {
    return $this->belongsTo('Group');
  }
}

and

class Role extends Eloquent {

  protected $table = 'role';

  public function accounts() {
    return $this->hasMany('Account');
  }

}

and database tables: accountand role

和数据库表:accountrole

account
-------
id
name
role_id (nullable)

role
----
id
name

And now the thing is:

现在的事情是:

I need to order accountsby role.namecolumn. But after join (or leftJoin) values are overriden by those from second table. Here's some code:

我需要accountsrole.name列订购。但是在 join(或 leftJoin)值被第二个表中的值覆盖后。这是一些代码:

$response = Account::with('role')->leftJoin('group', 'group.id', '=', 'account.group_id')->get();

After that values for idand nameare incorrect in eloquent collections.

该值之后idname在雄辩的集合不正确。

Also, i need the return to be eloquent type models as i'm returning back the response in JSON, where it is important that later in JS (after parsing JSON) i can do just account.role.name.

此外,我需要返回是雄辩的类型模型,因为我正在返回 JSON 中的响应,重要的是稍后在 JS 中(解析 JSON 之后)我可以只做account.role.name.

Changing names of fields in tables (like: id -> account_id, and: id -> role_id) would be an workaround, but that's not my case - need to have primary key named idfor every table.

更改表中字段的名称(例如:id -> account_id 和:id -> role_id)将是一种解决方法,但这不是我的情况 - 需要id为每个表命名主键。

[edit] Yep, so the question is simply: how to solve that problem?

[编辑] 是的,所以问题很简单:如何解决这个问题?

回答by beech

You can use 'select' like you would in a normal SQL query:

您可以像在普通 SQL 查询中一样使用“选择”:

$response = Account::with('role')
    ->select('account.*')
    ->leftJoin('group', 'group.id', '=', 'account.group_id')
    ->get();

http://laravel.com/docs/queries#selects

http://laravel.com/docs/queries#selects

回答by Angel Santiago Jaime Zavala

Complementing the answer given by @beech, you can use alias inside your select clause, that way you can fetch only the specific keys you need e.g.

补充@beech给出的答案,您可以在 select 子句中使用别名,这样您就可以只获取您需要的特定键,例如

Account::with('role')
    ->select('account.id AS account_id', 'role.id AS role_id', 'account.name AS account_name', 'role.name AS role_name')
    ->leftJoin('group', 'group.id', '=', 'account.group_id')
    ->get();