where("name", "=", "John") ->" />

高级 Wheres

群组化参数

有些时候你需要更高级的 where 子句,如「where exists」或嵌套的群组化参数。Laravel 的查询构造器也可以处理这样的情况:

DB::table("users")
            ->where("name", "=", "John")
            ->orWhere(function($query)
            {
                $query->where("votes", ">", 100)
                      ->where("title", "<>", "Admin");
            })
            ->get();

上面的查找语法会产生下方的 SQL:

select * from users where name = "John" or (votes > 100 and title <> "Admin")

Exists 语法

DB::table("users")
            ->whereExists(function($query)
            {
                $query->select(DB::raw(1))
                      ->from("orders")
                      ->whereRaw("orders.user_id = users.id");
            })
            ->get();

上面的查找语法会产生下方的 SQL:

select * from users
where exists (
    select 1 from orders where orders.user_id = users.id
)
文章导航