好的,所以我有以下两个模型: 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

现在的事情是:

我需要订购 accounts 经过 role.name 柱子。但在 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#selects

其他提示

补充给出的答案 @山毛榉, ,您可以在 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();
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top