yii2数据条件查询使用说明

PHP 投稿 61800 0 评论

yii2数据条件查询使用说明

Yii框架中的条件查询使用说明

$customers = Customer::find()->where($where)->all();

$where就是我们所谓的条件,条件的写法也根据查询数据的不同存在差异,那么如何用yii2的方式来写查询条件呢?

[[简单条件]]

// SQL: (type = 1) AND (status = 2).
$where = ['type' => 1, 'status' => 2]
 
// SQL:(id IN (1, 2, 3)) AND (status = 2)
$where = ['id' => [1, 2, 3], 'status' => 2]
 
//SQL:status IS NULL
$where = ['status' => null]

[[and]]:将不同的条件组合在一起,用法举例:

//SQL:`id=1 AND id=2`
$where = ['and', 'id=1', 'id=2']
 
//SQL:`type=1 AND (id=1 OR id=2)`
$where = ['and', 'type=1', ['or', 'id=1', 'id=2']]
 
//SQL:`type=1 AND (id=1 OR id=2)` //此写法'='可以换成其他操作符,例:in like != >=等
$where = [
    'and',
    ['=', 'type', 1],
    [
        'or',
        ['=', 'id', '1'],
        ['=', 'id', '2'],
    ]
]

[[or]]:

//SQL:`(type IN (7, 8, 9) OR (id IN (1, 2, 3)))`
$where = ['or', ['type' => [7, 8, 9]], ['id' => [1, 2, 3]]

[[not]]:

//SQL:`NOT (attribute IS NULL)`
$where = ['not', ['attribute' => null]]

[[between]]: not between 用法相同

//SQL:`id BETWEEN 1 AND 10`
$where = ['between', 'id', 1, 10]

[[in]]: not in 用法类似

//SQL:`id IN (1, 2, 3)`
$where = ['in', 'id', [1, 2, 3]] or $where = ['id'=>[1, 2, 3]]
 //IN条件也适用于多字段
$where = ['in', ['id', 'name'], [['id' => 1, 'name' => 'foo'], ['id' => 2, 'name' => 'bar']]]
 
//也适用于内嵌sql语句
$where = ['in', 'user_id', (new Query())->select('id')->from('users')->where(['active' => 1])]

[[like]]:

//SQL:`name LIKE '%tester%'`
$where = ['like', 'name', 'tester']
 
//SQL:`name LIKE '%test%' AND name LIKE '%sample%'`
$where = ['like', 'name', ['test', 'sample']]
 
//SQL:`name LIKE '%tester'`
$where = ['like', 'name', '%tester', false]

[[exists]]: not exists用法类似

//SQL:EXISTS (SELECT "id" FROM "users" WHERE "active"=1)
$where = ['exists', (new Query())->select('id')->from('users')->where(['active' => 1])]

此外,您可以指定任意运算符如下

//SQL:`id >= 10`
$where = ['>=', 'id', 10]
 
//SQL:`id != 10`
$where = ['!=', 'id', 10]

 可进行精准搜索和模糊搜索

$prCon=['and', 'user_id = 0',  "salesman = $whereition[sid]"];
if (isset($whereition['mobile']) && $whereition['mobile'])
{
    array_push($prCon, ['like','mobile',$whereition['mobile']]);
}

编程笔记 » yii2数据条件查询使用说明

赞同 (57) or 分享 (0)
游客 发表我的评论   换个身份
取消评论

表情
(0)个小伙伴在吐槽