Non esiste query
Sep 27 2020
Ho un problema con una query.
nella tabella dei post, ho posts.id, quindi, nella tabella delle revisioni, ho posts_id (chiave esterna -> posts.id), reviews.id. voglio interrogare quei posts_id che non esistono nella tabella delle revisioni (post_id).
sto usando i costruttori di query laravel. sto provando come ->
$r = DB::table('reviews') ->select(DB::raw('count(id) as rev_count, posts_id')) ->groupBy('posts_id') ->get(); foreach ($r as $rr) { $p = DB::table('posts')
->select('id')
->where('id', '!=', $rr->posts_id)
->get();
}
ho estratto con successo il valore. ma con troppa complessità, forse buggy. se c'è una query diretta per estrarlo?
Risposte
1 Sujitmohanty30 Sep 27 2020 at 19:03
Che ne dici di usare not exists,
Query SQL:
select *
from posts
where not exists
(select reviews.posts_id
from reviews
where reviews.posts_id = posts.id)
laravelQuery equivalente :
DB::table('posts')
->select('id')
->whereNotExists(function ($query) { $query->select("reviews.posts_id")
->from('reviews')
->whereRaw('reviews.posts_id = posts.id');
})
->get();
C'è anche questo link SO che potrebbe essere utile per te