SQL >> Base de Datos >  >> RDS >> Mysql

Eloquent whereIn entre tablas unidas

Tu enfoque actual puede devolver varias filas por elemento. Con Eloquent puedes usar whereHas:

$cats = [1, 2, 3];
$query = Item::with('listings');

foreach ($cats as $cat) {
    $query->whereHas('catitems', function($q) use ($cat) {
        $q->where('id', $cat);
    });
}

$items = $query->get();

Si es lento, usa JOIN con having:

$items = Item::with('listings')
    ->join('catitem_item', 'catitem_item.item_id', '=', 'items.id')
    ->whereIn('catitem_item.catitem_id', $cats)
    ->groupBy('items.id')
    ->having(DB::raw('COUNT(*)'), '=', count($cats))
    ->select('items.*')
    ->get();