0
PK가 복합 테이블에없는 테이블에서 레코드 목록을 가져 오려고합니다. 아래 표를 보시면 pool
에없는 candidates
을 모두 얻으려고합니다. 따라서이 경우에는 Eric
만 가져야합니다. 그러나 그것은 많은에 의해 자주 액세스하는 페이지에서, 우리의 매우 크고 빠르게 성장하는 데이터베이스에서 매우 비효율적 인 것 같습니다 https://laracasts.com/discuss/channels/eloquent/get-records-collection-if-not-exists-in-another-tableEloquent; 다른 테이블에 행이 없습니다.
$crashedCarIds = CrashedCar::pluck('car_id')->all();
$cars = Car::whereNotIn('id', $crashedCarIds)->select(...)->get();
작동합니다 :
+-------------+ +-------------+
| candidates | | pools |
+-------------+ +-------------+
| id | name | | id | name |
+----+--------| +----+--------|
| 1 | John | | 1 | Pool A |
| 2 | Richard| | 2 | Pool B |
| 3 | Eric | | 3 | Pool C |
+----+--------+ +----+--------+
+--------------------------+
| candidate_pools |
+--------------------------+
| pool_id | candidate_id |
+---------+----------------|
| 1 | 1 |
| 1 | 2 |
| 3 | 2 |
| 2 | 1 |
+---------+----------------+
나는이 대답을 발견했습니다 사람들의.
정상 MySQL의에서이 같은 일을 할 것입니다 :WHERE candidates.id NOT IN
(SELECT candidate_id
FROM candidate_pools
LEFT JOIN pools
ON candidate_pools.pool_id = pool.id
)
참고 : 테이블은 단순한 그림이지만, 실제 데이터베이스 설정 및 쿼리 많이 크다.
는public function scopeNotInPool($query) {
$query->whereNotIn('candidate_id', function ($query) {
$query->select('candidate_id')
->from('candidate_pool')
->join('pool', function ($join) {
$join->on('pool.id', '=', 'candidate_pool.pool_id');
}
)
;
});
return $query;
}
그런 다음 원하는 전화 :
$candidates = Models\Candidate::notInPool()->get();
왜 당신은 당신의 모델 웅변 관계를 설정하지 않는 –
@RutvijKothari 감사합니다.하지만 내 질문과 관련이 없습니다. – Richard