Laravel eloquent - prevent overriding values when joining tables
Question
Ok, so i have following two models: Account
and Role
class Account extends Eloquent
{
protected $table = 'account';
/* [...] */
public function group() {
return $this->belongsTo('Group');
}
}
and
class Role extends Eloquent {
protected $table = 'role';
public function accounts() {
return $this->hasMany('Account');
}
}
and database tables: account
and role
account
-------
id
name
role_id (nullable)
role
----
id
name
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();
After that values for id
and name
are incorrect in eloquent collections.
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
.
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?
Solution
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();
OTHER TIPS
Complementing the answer given by @beech, you can use alias inside your select clause, that way you can fetch only the specific keys you need e.g.
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();