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:

我要订accounts*role.name栏.但after join(或leftJoin)值被第二个表中的值覆盖.以下是一些代码:

$response = Account::with('role')->leftJoin('group', 'group.id', '=', 'account.group_id')->get();

After that values for id and name are incorrect in eloquent collections.

另外,我需要返回Eloquent 的类型模型,因为我要用JSON返回响应,在JS中稍后(在解析JSON之后)我只能返回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.

[编辑]

推荐答案

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相关问答推荐

如何通过单击进入 vs 代码中的类

如何在 Laravel 中填充以后执行的条件

Laravel 5 控制台( artisan )命令单元测试

Laravel 5.4 - 如何为同一个自定义验证规则使用多个错误消息

判断 Laravel 中是否存在唯一索引键

Laravel + SQLite = SQLSTATE[HY000]一般错误:8次try 写入只读数据库

磁盘 [视频] 没有配置的驱动程序

克隆后设置 Laravel 项目

在 laravel 查询构建器中使用多个 where 子句

在 laravel 如何将额外的数据传递给 mutators 和 accessors

如何在 Laravel 中为模型命名,以免与现有类发生冲突?

如何在 Laravel Eloquent 中 Select 某些字段?

如何处理 laravel 5 中的私有图像?

调用未定义的方法 Illuminate\Foundation\Application::bindShared()

laravel:Eloquent的例子将数据插入数据库

如何在laravel 5.1中使用url(路由)传递多个参数

Laravel 获取文件内容

如何在 laravel 表单验证错误消息中给出自定义字段名称

Laravel Mix:更新 Node.js 依赖项

Laravel 4 控制器模板/Blade - 正确的方法?