【问题标题】:Where not Exists en LaravelLaravel 哪里不存在
【发布时间】:2018-06-06 03:39:06
【问题描述】:

谁能告诉我我的 laravel 查询中可能有什么错误,基本上我想要列出一个表的记录,其 id 与另一个表不相关。我用这个查询在 Mysql 中做到了:SELECT * FROM item WHERE NOT EXISTS (SELECT null FROMqualities WHERE Grades.item_id = item.id ANDqualities.user_id = 2);

但现在我需要在 laravel 中执行相同的查询,我尝试过这种方式: codigo

我得到的是这个我不知道如何解决的语法错误: error

我非常感谢任何可以告诉我我做错了什么,或者我在 Laravel 中以什么形式进行查询的人。

【问题讨论】:

  • 请用英文提问..
  • 用英文分享。尝试使用谷歌翻译。并添加代码而不是图像
  • whereRaw 需要 1 或 2 个参数 - 可以是带有整个 where 子句的字符串,或者是带有占位符和绑定数组的字符串。

标签: mysql laravel where-clause


【解决方案1】:

您还可以将查询重写为左连接,例如

SELECT i.*
FROM item i
LEFT JOIN qualifications q ON q.item_id = i.id  AND q.user_id = 2
WHERE q.item_id IS NULL

在查询生成器中,您可以将其编写为

DB::table('item as i')
    ->select('i.*')
    ->leftJoin('qualifications as q', function ($join) use($user_id) {
        $join->on('q.item_id', '=', 'i.id')
             ->on('q.user_id', '=', $user_id);
    })
    ->whereNull('q.item_id')
    ->get();

我建议您采用的另一种方法是设置您的关系和模型,并以雄辩的方式进行

class Item extends Model
{
    public function qualifications()
    {
        return $this->hasMany(\App\Models\Qualification::class, 'item_id');
    }
}

class Qualification extends Model
{
    public function qualifications()
    {
        return $this->belongsTo(Item::class, 'item_id');
    }
}

然后你可以使用Querying Relationship Absence

Item::whereDoesntHave('qualifications', function ($query) use($user_id) {
    $query->where('user_id', '=', $user_id);
})->get();

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-11-08
    • 1970-01-01
    • 2022-07-29
    • 2018-09-25
    • 1970-01-01
    • 2020-04-20
    • 2015-04-22
    相关资源
    最近更新 更多