如何在laravel中写一个where not in query?

How to write a where not in query in laravel?

我想在 laravel 中写一个 Where not in 查询。我在 sql 中写道它工作正常请帮助我将查询转换为 laravel。

这是查询...

SELECT * 
FROM `apiaccessauth` 
WHERE `site_name` NOT IN (
                SELECT `site_name` 
                FROM `API_site_access_log` 
                WHERE `created_at` LIKE '%2021-10-15%'
                );

如果要使用Eloquent,会像下面这样

Eloquent 型号

<?php

namespace App\Modules\Vehicle\Models;

use Illuminate\Database\Eloquent\Model;

class ApiAccessAuth extends Model
{
    protected $table = 'apiaccessauth';
}

您的查询

ApiAccessAuth::whereNotIn('site_name', function ($query) {
    $query->from('API_site_access_log')
        ->select('site_name')
        ->whereDate('created_at', '2021-10-15');
})->get();

如果你想使用查询生成器,它会像下面这样

use Illuminate\Support\Facades\DB;

DB::table('apiaccessauth')
    ->whereNotIn('site_name', function ($query) {
        $query->from('API_site_access_log')
            ->select('site_name')
            ->whereDate('created_at', '2021-10-15');
    })->get();

也许您想将查询重构为


    SELECT a.* 
    FROM `apiaccessauth` a, 
    `API_site_access_log` b 
    WHERE
    a.`site_name` = b.`site_name` AND
    b.`site_name` NOT LIKE '%2021-10-15%'

因此使用查询构建器


    $result = DB::table('apiaccessauth')
    ->join('API_site_access_log', 'API_site_access_log.site_name', '=', 'apiaccessauth.site_name')
    ->where('API_site_access_log.site_name', 'not like', "%2021-10-15%")
    ->get();

也许你需要一个左连接或外连接,这取决于你想要什么