Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel eloquent - prevent overriding values when joining tables

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?

like image 418
plunntic iam Avatar asked Jun 03 '14 14:06

plunntic iam


1 Answers

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

like image 50
beech Avatar answered Sep 23 '22 02:09

beech