高級 Wheres

2018-02-24 15:52 更新

群組化參數(shù)

有些時候你需要更高級的 where 子句,如「where exists」或嵌套的群組化參數(shù)。Laravel 的查詢構(gòu)造器也可以處理這樣的情況:

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

上面的查找語法會產(chǎn)生下方的 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();

上面的查找語法會產(chǎn)生下方的 SQL:

select * from users
where exists (
    select 1 from orders where orders.user_id = users.id
)
以上內(nèi)容是否對您有幫助:
在線筆記
App下載
App下載

掃描二維碼

下載編程獅App

公眾號
微信公眾號

編程獅公眾號