[英]Laravel. Using WHERENOTIN
Basically I want to build tihs query in Laravel, but it does not work. 基本上我想在Laravel中建立该查询,但它不起作用。
SELECT films.id, films.name AS film
FROM films
WHERE films.id NOT IN
(
SELECT films.id
FROM actors, actor_film, films
WHERE actors.id = actor_film.actor_id
AND actor_film.film_id = films.id
GROUP BY films.id
)
ORDER BY films.id DESC
LIMIT 600
;
Using a "whereNotIn" I have written these two queries: The first one get all films in the Data Base that has at least an actor associated like this: 使用“ whereNotIn”,我编写了以下两个查询:第一个查询获取数据库中至少具有这样一个演员的所有电影:
$films_with_actors = DB::table('films')
->join('actor_film', 'actor_film.film_id', '=', 'films.id')
->join('actors', 'actors.id', '=', 'actor_film.actor_id')
->select( 'films.id')
->groupBy('films.id')
->get();
Now I want to get the films that do not have associated an actor. 现在,我要获得与演员没有关联的电影。 For that I am trying to get the ID that are not included in the previous method, like this:
为此,我试图获取之前方法中未包含的ID,如下所示:
$films_with_no_actors = DB::table('films')
->whereNotIn('films.id', $films_with_actors)
->orderBy('films.id', 'desc')
->take(500)
->get();
-
Any help? 有什么帮助吗?
I am giving you a basic solution based on the code you shared. 我正在根据您共享的代码为您提供基本的解决方案。
In laravel you have a method called pluck for retrieving an array with all the values for a given key. 在laravel有一个名为方法采摘检索阵列与一个给定键的所有值。
Therefore, you can get only the ids for the $films_with_actors. 因此,您只能获取$ films_with_actors的ID。 Something like (based on your first query):
类似(根据您的第一个查询):
$films_with_actors = DB::table('films')
->join('actor_film', 'actor_film.film_id', '=', 'films.id')
->join('actors', 'actors.id', '=', 'actor_film.actor_id')
->select( 'films.id')
->groupBy('films.id')
->pluck('id')->toArray();
Now you have an array with the ids and you can include that array in the whereNotIn clause of your second query: 现在,您有了一个带有ID的数组,可以将该数组包含在第二个查询的whereNotIn子句中:
$films_with_no_actors = DB::table('films')
->whereNotIn('films.id', $films_with_actors)
->orderBy('films.id', 'desc')
->take(500)
->get();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.