質問

OK、私は次の2つのモデルを持っています:AccountRole

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');
  }

}
.

とデータベース表:accountrole

account
-------
id
name
role_id (nullable)

role
----
id
name
.

そして今のことは:

accounts列でrole.nameを注文する必要があります。しかし、結合(またはleftjoin)の値は、2番目のテーブルからのものによって上書きされます。これがいくつかのコードです:

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

idおよびnameの値が誤ったコレクションで正しくない。

また、JSONでの返信を返しているので、JSONでの返信を返しているので、JSON(JSONを解析した後)が重要であることが重要です。

テーブル内のフィールド名の変更(id - > account_id、および:id - > role_id)は回避策になりますが、それは私の場合ではありません。

[編集] うん、その問題は単にその問題を解決する方法?

役に立ちましたか?

解決

通常のSQLクエリのように 'select'を使用できます。

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

http://larvel.com/docs/queries##

他のヒント

@beech で与えられた回答を補完すると、SELECT句内のエイリアスを使用することができます。そのようにして、必要な特定のキーのみを取得できます。

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();
.

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top