好的,所以我有以下两个模型: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
进行排序。但在 join(或 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
的主键每张 table 。
[编辑] 是的,所以问题很简单:如何解决这个问题?
最佳答案
您可以像在普通 SQL 查询中一样使用“select”:
$response = Account::with('role')
->select('account.*')
->leftJoin('group', 'group.id', '=', 'account.group_id')
->get();
关于php - Laravel eloquent - 防止连接表时覆盖值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24018304/