【发布时间】:2014-07-23 23:22:38
【问题描述】:
好的,所以我有以下两个模型:Account 和 Role
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');
}
}
和数据库表:account 和 role
account
-------
id
name
role_id (nullable)
role
----
id
name
现在的事情是:
我需要通过role.name 列订购accounts。但是在加入(或 leftJoin)之后,值会被第二个表中的值覆盖。这是一些代码:
$response = Account::with('role')->leftJoin('group', 'group.id', '=', 'account.group_id')->get();
之后 id 和 name 的值在 eloquent 集合中不正确。
另外,我需要返回是 eloquent 类型的模型,因为我正在返回 JSON 中的响应,重要的是稍后在 JS 中(解析 JSON 之后)我可以只做 account.role.name。
更改表中字段的名称(例如:id -> account_id 和:id -> role_id)是一种解决方法,但我的情况并非如此 - 需要为每个表指定名为 id 的主键。
[编辑] 是的,所以问题很简单:如何解决这个问题?
【问题讨论】: