数据库查询实例(findOne、findAll、where)

findOne()和findAll():

// 查询key值为10的客户
$customer = Customer::findOne(10);
$customer = Customer::find()->where(['id' => 10])->one();
// 查询年龄为30,状态值为1的客户
$customer = Customer::findOne(['age' => 30, 'status' => 1]);
$customer = Customer::find()->where(['age' => 30, 'status' => 1])->one();
// 查询key值为10的所有客户
$customers = Customer::findAll(10);
$customers = Customer::find()->where(['id' => 10])->all();
// 查询key值为1011,12的客户
$customers = Customer::findAll([10, 11, 12]);
$customers = Customer::find()->where(['id' => [10, 11, 12]])->all();
// 查询年龄为30,状态值为1的所有客户
$customers = Customer::findAll(['age' => 30, 'status' => 1]);
$customers = Customer::find()->where(['age' => 30, 'status' => 1])->all();

where()条件:

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

$cond写法举例:

// SQL: (type = 1) AND (status = 2).
$cond = ['type' => 1, 'status' => 2] 

// SQL:(id IN (1, 2, 3)) AND (status = 2)
$cond = ['id' => [1, 2, 3], 'status' => 2] 

//SQL:status IS NULL
$cond = ['status' => null]

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

//SQL:`id=1 AND id=2`
$cond = ['and', 'id=1', 'id=2']

//SQL:`type=1 AND (id=1 OR id=2)`
$cond = ['and', 'type=1', ['or', 'id=1', 'id=2']]

or

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

not

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

between、[not between] 用法相同

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

in、[not in] 用法类似

//SQL:`id IN (1, 2, 3)`
$cond = ['in', 'id', [1, 2, 3]]

//IN条件也适用于多字段
$cond = ['in', ['id', 'name'], [['id' => 1, 'name' => 'foo'], ['id' => 2, 'name' => 'bar']]]

//也适用于内嵌sql语句
$cond = ['in', 'user_id', (new Query())->select('id')->from('users')->where(['active' => 1])]

like

//SQL:`name LIKE '%tester%'`
$cond = ['like', 'name', 'tester']

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

//SQL:`name LIKE '%tester'`
$cond = ['like', 'name', '%tester', false]

exists、not exists 用法类似

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

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

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

//SQL:`id != 10`
$cond = ['!=', 'id', 10]
  • 1
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值