問題描述
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)值被第二個表中的值覆蓋后.這是一些代碼:
And now the thing is:
I need to order accounts
by role.name
column. But after join (or leftJoin) values are overriden by those from second table. Here's some code:
$response = Account::with('role')->leftJoin('group', 'group.id', '=', 'account.group_id')->get();
之后 id
和 name
的值在 eloquent 集合中不正確.
After that values for id
and name
are incorrect in eloquent collections.
此外,我需要返回的是 eloquent 類型模型,因為我以 JSON 返回響應,重要的是稍后在 JS 中(解析 JSON 后)我可以只做 account.role.name
.
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
.
更改表中字段的名稱(例如:id -> account_id 和:id -> role_id)將是一種解決方法,但這不是我的情況 - 需要將主鍵命名為 id
每張桌子.
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 id
for every table.
是的,所以問題很簡單:如何解決這個問題?
[edit] Yep, so the question is simply: how to solve that problem?
推薦答案
您可以像在普通 SQL 查詢中一樣使用選擇":
You can use 'select' like you would in a normal SQL query:
$response = Account::with('role')
->select('account.*')
->leftJoin('group', 'group.id', '=', 'account.group_id')
->get();
http://laravel.com/docs/queries#selects
這篇關于Laravel eloquent - 在加入表時防止覆蓋值的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!