简体   繁体   中英

Laravel. Using WHERENOTIN

Basically I want to build tihs query in Laravel, but it does not work.

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:

    $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:

    $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.

Therefore, you can get only the ids for the $films_with_actors. 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:

    $films_with_no_actors = DB::table('films')
    ->whereNotIn('films.id', $films_with_actors)
    ->orderBy('films.id', 'desc')
    ->take(500)
    ->get();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM