Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

212
Visualizações
Laravel where not

I need to replicate this query with Eloquent QueryBuilder:

select * from table_name
where type = 'custom_type' 
and not
(
(topable_type = 'Car' and topable_id = 1)
or 
(topable_type = 'Car' and topable_id = 2)
)

The problem comes with the and not part. As far as I can see Laravel does not support "whereNot" functionality.

Edit: Code attempt:

$deleteQuery = Item::where('type', '=', $type);
foreach ($except as $exceptItem) {
  $deleteQuery = $deleteQuery->where(fn($query) => $query->where('topable_type', '!=', $exceptItem->type)->where('topable_id', '!=', $exceptItem->id));
}
$deleteQuery->delete();

Edit2: With Tim Lewis'es help I modified my previous attempt and it's working now:

$deleteQuery = Item::where('type', $type);

foreach ($except as $exceptItem) {
    $deleteQuery = $deleteQuery->where(fn($query) => $query->where('topable_type', $topableItem->type)->where('topable_id', $topableItem->id)
            , null, null, 'and not');
}
        
$deleteQuery->delete();

It doesn't generate exact query as I mentioned above, but pretty similair and it works as expected.

over 4 years ago · Santiago Trujillo
1 Respostas
Responde à pergunta

0

You can do chained where condition

Item::where('type','custom_type')->where(function ($query){
      $query->where(function ($query){
          $query->where('topable_type','Car');
          $query->where('topable_id',1);
      });

        $query->orwhere(function ($query){
            $query->where('topable_type','Car');
            $query->where('topable_id',2);
        });
    },null, null, 'and not')->get();

Ref:https://github.com/laravel/ideas/issues/708

over 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda