Laravel Eloquent - テーブルを接合するときの値の上書きを防ぐ
質問
OK、私は次の2つのモデルを持っています:Account
とRole
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
.
そして今のことは:
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();
.
他のヒント
@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();
. 所属していません StackOverflow