Laravel雄辩-防止在连接表时重写值


Laravel eloquent - prevent overriding values when joining tables

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

class Account extends Eloquent
{
  protected $table = 'account';
  /* [...] */
  public function group() {
    return $this->belongsTo('Group');
  }
}

class Role extends Eloquent {
  protected $table = 'role';
  public function accounts() {
    return $this->hasMany('Account');
  }
}

和数据库表:accountrole

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

现在是:

我需要按role.name列排序accounts。但是在join(或leftJoin)之后,值将被第二个表中的值覆盖。下面是一些代码:

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

之后,idname的值在雄辩集合中是不正确的。

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

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

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

您可以像在普通SQL查询中一样使用'select':

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

http://laravel.com/docs/queries选择

补充@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();

如果希望选择所有字段并避免覆盖特定表,请将其添加为最后一个选择表->select('group.*', 'account.*') .

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