TP5.1高級查詢

一、多個Where

Db::table('think_user')
    ->where('name|title','like','thinkphp%')
    ->where('create_time&update_time','>',0)
    ->find();

二、多個Where的區間查詢

Db::table('think_user')
    ->where('name', ['like', '%thinkphp%'], ['like', '%kancloud%'], 'or')
    ->where('id', ['>', 0], ['<>', 10], 'and')
    ->find();

生成SQL如下:

SELECT * FROM `think_user` WHERE ( `name` LIKE '%thinkphp%' OR `name` LIKE '%kancloud%' ) AND ( `id` > 0 AND `id` <> 10 ) LIMIT 1

區間查詢的查詢條件必須使用數組定義方式,支持所有的查詢表達式。

區間查詢其實可以用下面的方式替代,更容易理解,因爲查詢構造器支持對同一個字段多次調用查詢條件,例如:

Db::table('think_user')
    ->where('name', 'like', '%think%')
    ->where('name', 'like', '%php%')
    ->where('id', 'in', [1, 5, 80, 50])
    ->where('id', '>', 10)
    ->find();

三、批量(字段)查詢

可以進行多個條件的批量條件查詢定義,例如:

Db::table('think_user')
    ->where([
        ['name', 'like', 'thinkphp%'],
        ['title', 'like', '%thinkphp'],
        ['id', '>', 0],
        ['status', '=', 1],
    ])
    ->select();

生成SQL如下:

SELECT * FROM `think_user` WHERE `name` LIKE 'thinkphp%' AND `title` LIKE '%thinkphp' AND `id` > 0 AND `status` = '1'

注意,V5.1.7+版本數組方式如果使用exp查詢的話,一定要用raw方法。

 

Db::table('think_user')
    ->where([
        ['name', 'like', 'thinkphp%'],
        ['title', 'like', '%thinkphp'],
        ['id', 'exp', Db::raw('>score')],
        ['status', '=', 1],
    ])
    ->select();

 

詳情見:https://www.kancloud.cn/manual/thinkphp5_1/354030

常用留個筆記!

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章