Laravel Eloquent - 테이블에 가입 할 때 값을 무시하지 않습니다
문제
OK, 그래서 두 가지 모델이 있습니다 : 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
를 주문해야합니다. 그러나 결합 (또는 leteJoin) 값이 두 번째 테이블의 값으로 재정의됩니다. 여기 몇 가지 코드가 있습니다 :
$response = Account::with('role')->leftJoin('group', 'group.id', '=', 'account.group_id')->get();
.
id
및 name
의 값이 eLoquent 컬렉션에서 잘못되었습니다.
또한 JSON의 응답을 되돌려 놓는 것처럼 웅변적인 유형 모델로 돌아가는 것이 필요합니다. JS에서 나중에 (JSON 구문 분석 한 후) account.role.name
를 할 수 있습니다.
테이블의 필드 이름을 변경합니다 (예 : id -> account_id, id -> role_id)는 해결 방법이지만 내 경우가 아닙니다. 모든 테이블에 대해 id
라는 기본 키가 필요합니다.
[편집] 옙, 그래서 질문은 단순히 그 문제를 해결하는 방법입니까?
해결책
일반적인 SQL 쿼리에서와 같이 '선택'을 사용할 수 있습니다.
$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