在 NOT IN 中创建子查询

Create subquery in NOT IN

我正在使用 Laravel Framework 6.16.0

我有以下 sql 查询:

SELECT DISTINCT
    `companies`.*
FROM
    `companies`
LEFT JOIN `trx` ON `trx`.`companies_id` = `companies`.`id`
WHERE
    `trx`.`transaction_date` >= 2020-11-12 AND companies.symbol NOT IN (SELECT DISTINCT
        companies.symbol
    FROM
        `companies`
    LEFT JOIN articles a ON a.companies_id = companies.id
    WHERE
        a.created_at >= 2020-11-12 
    ORDER BY
        created_at
    DESC)
ORDER BY
    transaction_date
DESC
    

我创建了以下 eloquent 查询:

    DB::connection('mysql_prod')->table('companies')->select('companies.symbol')
                ->leftJoin('trx', 'trx.companies_id', '=', 'companies.id')
                ->where('trx.transaction_date', '>=', Carbon::today()->subDays(1)->startOfDay())
                ->orderBy('transaction_date', 'desc')
                ->distinct()
                ->get('symbol');

但是,我不确定如何在我的 eloquent 查询中打包以获取所有应该排除的 symbol 返回。

非常感谢您的回复!

你应该尝试这样的事情:

$date = Carbon::today()->subDays(1)->startOfDay();
DB::connection('mysql_prod')->table('companies')->select('companies.symbol')
                ->leftJoin('trx', 'trx.companies_id', '=', 'companies.id')
                ->where('trx.transaction_date', '>=', $date)
                ->whereNotIn('companies.symbol', function ($q) use ($date) => {
                    $q->select('companies.symbol')
                      ->from('companies')
                      ->leftJoin('articles', 'articles.companies_id', 'companies.id')
                      ->where('articles.created_at', '>', $date)
                      ->distinct()
                      ->get()
                })
                ->orderBy('transaction_date', 'desc')
                ->distinct()
                ->get();

它将提供与您提到的类似的查询。

引用自here

此外,您可以阅读如何编写子查询 Laravel docs

检查 以找到您需要的内容。