参考文档:http://www.yiiframework.com/doc-2.0/yii-db-activequery.html
参考文档:http://www.yiichina.com/doc/guide/2.0/db-dao
参考文档:https://getyii.com/topic/358
保存之前 / 更新之前 / 插入之前 / 更新以后 / 插入以后
yii2 查询sql时,字段被强制加反引号`导致SQL执行失败
yii2 使用find,update静态方法时,命名空间通过变量名传参使用方式
- Customer::find()->one(); 此方法返回一条数据;
- Customer::find()->all(); 此方法返回所有数据;
- Customer::find()->count(); 此方法返回记录的数量;
- Customer::find()->average(); 此方法返回指定列的平均值;
- Customer::find()->min(); 此方法返回指定列的最小值 ;
- Customer::find()->max(); 此方法返回指定列的最大值 ;
- Customer::find()->scalar(); 此方法返回值的第一行第一列的查询结果;
- Customer::find()->column(); 此方法返回查询结果中的第一列的值;
- Customer::find()->exists(); 此方法返回一个值指示是否包含查询结果的数据行;
- Customer::find()->batch(10); 每次取10条数据
- Customer::find()->each(10); 每次取10条数据,迭代查询
- //根据sql语句查询:查询name=test的客户
- Customer::model()->findAllBySql("select * from customer where name = test");
- //根据主键查询:查询主键值为1的数据
- Customer::model()->findByPk(1);
- //根据条件查询(该方法是根据条件查询一个集合,可以是多个条件,把条件放到数组里面)
- Customer::model()->findAllByAttributes(['username'=>'admin']);
- //子查询
- $subQuery = (new Query())->select('COUNT(*)')->from('customer');
- // SELECT `id`, (SELECT COUNT(*) FROM `customer`) AS `count` FROM `customer`
- $query = (new Query())->select(['id', 'count' => $subQuery])->from('customer');
- //关联查询:查询客户表(customer)关联订单表(orders),条件是status=1,客户id为1,从查询结果的第5条开始,查询10条数据
- $data = (new Query())
- ->select('*')
- ->from('customer')
- ->join('LEFT JOIN','orders','customer.id = orders.customer_id')
- ->where(['status'=>'1','customer.id'=>'1'])
- ->offset(5)
- ->limit(10)
- ->all()
use yii\db\Query;
- <?php
- $plans = ModPlan::find()
- ->from(["plan" => ModPlan::tableName()]) //设置别名
- //->select("plan.*,enroll.plan_id as en_plan_id,enroll.limited")
- ->where($conditions)
- ->leftJoin(Enroll::tableName()." AS enroll","enroll.plan_id=plan.plan_id")
- ->limit($perpage)
- ->offset($offset)
- ->indexBy('plan_id')
- ->orderBy('plan_bt desc');
- // ->asArray()
- // ->all();
- print_r($plans->createCommand()->getRawSql());
- echo '<hr>';
- // 省掉asArray 转换这一步
- $plans = (new \yii\db\Query())
- ->select('*')
- ->from('plan as pl')
- ->join('LEFT JOIN','pl_enroll as en','en.plan_id = pl.plan_id')
- ->where(['pl.plan_id'=>'4'])
- ->offset(5)
- ->limit(10);
- //->all();
- print_r($plans->createCommand()->getRawSql());
- //print_r($plans);
- die;
打印SQL语句:
- $model->find()->createCommand()->getRawSql();
在生成的model中,查询指定ID的一条查询为:
- $model = $this->findModel($id);
想要将它转换为数组就发现asArray()失效了,或者报错了,这时候可以用:(不推荐)
- $model = $this->findModel($id);
- $model->attributes;
- $customers = Customer::findBySql('SELECT * FROM customer')->all();
基础语句:
- $customers = Customer::find()->where($cond)->all();
- // $cond就是我们所谓的条件,条件的写法也根据查询数据的不同存在差异,那么如何用yii2的方式来写查询条件呢?
简单条件:
- // 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']]
- //SQL:`type=1 AND (id=1 OR id=2)` //此写法'='可以换成其他操作符,例:in like != >=等
- $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:`(type IN (7, 8, 9) OR (id IN (1, 2, 3)))`
- $cond = ['or', ['type' => [7, 8, 9]], ['id' => [1, 2, 3]]
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]] or $cond = ['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])]
isnull
- $cond = ['IS','name',null];
此外,您可以指定任意运算符如下
- //SQL:`id >= 10`
- $cond = ['>=', 'id', 10]
- //SQL:`id != 10`
- $cond = ['!=', 'id', 10]
使用model::save()操作进行新增数据
- $user= new User;
- $user->username =$username;
- $user->password =$password;
- $user->save()
或:
- <?php
- /**
- * model层
- * 一定要把字段定义在model层rouls方法中
- * 使用setAttributes的第二个参数$safeOnly,设置为false,表示不检测字段安全
- $model->setAttributes(array('title'=>'小白','content'=>'lala'),false);
- */
- public function rules(){
- return [
- [['user_id', 'readed', 'modifie_user', 'published'], 'integer'],
- [['user_name', 'title', 'meta_rule'], 'string', 'max' => 32],
- [['abstract'], 'string', 'max' => 512],
- [['image', 'meta_title'], 'string', 'max' => 128],
- [['context'], 'string', 'max' => 8192],
- [['meta_keyword', 'meta_description'], 'string', 'max' => 256],
- [['meta_title','meta_keyword','meta_description','image'], 'default', 'value' => ''],
- [['title','context'], 'required']
- ];
- }
- public function add($data){
- $this->setAttributes($data);
- $this->isNewRecord = true;
- $this->save();
- return $this->id;
- }
- //入库二维数组
- public function addAll($data){
- $ids=array();
- foreach($data as $attributes)
- {
- $this->isNewRecord = true;
- $this->setAttributes($attributes);
- $this->save()&& array_push($ids,$this->id) && $this->id=0;
- };
- return $ids;
- }
- /**
- * 控制器
- */
- public function actionAdd(){
- $model = new Model();
- $data = array(
- "title"=>"小白",
- "content"=>"lala"
- );
- $id = $model->add($data);
- echo $id;
- // $data=array(
- // array(
- // "title"=>"小白",
- // "content"=>"lala"
- // ),
- // array(
- // "title"=>"小hong",
- // "content"=>"66"
- // )
- // );
- // $ids=$model->addAll($data);
- // var_dump($ids);
- }
updateAll()
For example, to change the status to be 1 for all customers whose status is 2
- Customer::updateAll(['status' => 1], 'status = 2');
批量设置指定字段加1
- // 所有客户的age(年龄)字段加1:
- Customer::updateAllCounters(['age' => 1]);
用于数字类型,将值进行 累加 或者 累减
$count = 1, 就是加一
$count = -1, 就是减一
User::updateAllCounters(['sort' => $count], ['id' => 2]);
如果插入失败,打印错误日志:
- if ($model->validate()) {
- $model->save();
- } else {
- var_dump($model->errors);
- }
新增失败,打印错误日志:
- <?php
- $model->save();
- if($model->hasErrors()) {
- print_r($model->errors);
- exit;
- throw new Exception($model->hasErrors());
- }
- <?php
- $moduleModel->load(Yii::$app->request->post());
- $moduleModel->id = $model->id;
- $moduleModel->save();
- if($moduleModel->hasErrors()) {
- throw new Exception(current($moduleModel->getFirstErrors()));
- print_r($moduleModel->error);
- die;
- }
使用createCommand()进行新增数据
- Yii::$app->db->createCommand()->insert('user', [
- 'name' => 'test',
- 'age' => 30,
- ])->execute();
获取最后一次插入的ID:
- $model->save();
- //得到上次插入的Insert id
- $id = $model->attributes['id'];
- $id = Yii::$app->db->getLastInsertId();
批量插入数据
- Yii::$app->db->createCommand()->batchInsert('user', ['name', 'age'], [
- ['test01', 30],
- ['test02', 20],
- ['test03', 25],
- ])->execute();
第一种方法
- $model = new User();
- foreach($data as $attributes)
- {
- $_model = clone $model;
- $_model->setAttributes($attributes);
- $_model->save();
- }
第二种
- $model = new User();
- foreach($data as $attributes)
- {
- $model->isNewRecord = true;
- $model->setAttributes($attributes);
- $model->save() && $model->id=0;
- }
使用model::save()进行修改
- $user = User::find()->where(['name'=>'test'])->one(); //获取name等于test的模型
- $user->age = 40; //修改age属性值
- $user->save(); //保存
直接修改:修改用户test的年龄为40
- $result = User::model()->updateAll(['age'=>40],['name'=>'test']);
使用createCommand()修改
- Yii::$app->db->createCommand()->update('user', ['age' => 40], 'name = test')->execute();
使用model::delete()进行删除
- $user = User::find()->where(['name'=>'test'])->one();
- $user->delete();
直接删除:删除年龄为30的所有用户
- $result = User::deleteAll(['age'=>'30']);
根据主键删除:删除主键值为1的用户
- $result = User::deleteByPk(1);
使用createCommand()删除
- Yii::$app->db->createCommand()->delete('user', 'age = 30')->execute();
- one(): 根据查询结果返回查询的第一条记录。
- all(): 根据查询结果返回所有记录。
- count(): 返回记录的数量。
- sum(): 返回指定列的总数。
- average(): 返回指定列的平均值。
- min(): 返回指定列的最小值。
- max(): 返回指定列的最大值。
- scalar(): 返回查询结果的第一行中的第一列的值。
- column(): 返回查询结果中的第一列的值。
- exists(): 返回一个值,该值指示查询结果是否有数据。
- where(): 添加查询条件
- with(): 该查询应执行的关系列表。
- indexBy(): 根据索引的列的名称查询结果。
- asArray(): 以数组的形式返回每条记录。
应用实例:
- Customer::find()->one(); 此方法返回一条数据;
- Customer::find()->all(); 此方法返回所有数据;
- Customer::find()->count(); 此方法返回记录的数量;
- Customer::find()->average(); 此方法返回指定列的平均值;
- Customer::find()->min(); 此方法返回指定列的最小值 ;
- Customer::find()->max(); 此方法返回指定列的最大值 ;
- Customer::find()->scalar(); 此方法返回值的第一行第一列的查询结果;
- Customer::find()->column(); 此方法返回查询结果中的第一列的值;
- Customer::find()->exists(); 此方法返回一个值指示是否包含查询结果的数据行;
- Customer::find()->asArray()->one(); 以数组形式返回一条数据;
- Customer::find()->asArray()->all(); 以数组形式返回所有数据;
- Customer::find()->where($condition)->asArray()->one(); 根据条件以数组形式返回一条数据;
- Customer::find()->where($condition)->asArray()->all(); 根据条件以数组形式返回所有数据;
- Customer::find()->where($condition)->asArray()->orderBy('id DESC')->all(); 根据条件以数组形式返回所有数据,并根据ID倒序;
2.关联查询:
- ActiveRecord::hasOne():返回对应关系的单条记录
- ActiveRecord::hasMany():返回对应关系的多条记录
hasone新版更新,classname() 改为 class
如:
- public function getUser(){
- if($this->aid){
- return $this->hasOne(PersonnelManage::class,['id'=>'aid']);
- }
- }
应用实例:
- //客户表Model:CustomerModel
- //订单表Model:OrdersModel
- //国家表Model:CountrysModel
- //首先要建立表与表之间的关系
- //在CustomerModel中添加与订单的关系
- Class CustomerModel extends yiidbActiveRecord
- {
- ...
- public function getOrders()
- {
- //客户和订单是一对多的关系所以用hasMany
- //此处OrdersModel在CustomerModel顶部别忘了加对应的命名空间
- //id对应的是OrdersModel的id字段,order_id对应CustomerModel的order_id字段
- return $this->hasMany(OrdersModel::className(), ['id'=>'order_id']);
- }
- public function getCountry()
- {
- //客户和国家是一对一的关系所以用hasOne
- return $this->hasOne(CountrysModel::className(), ['id'=>'Country_id']);
- }
- ....
- }
- // 查询客户与他们的订单和国家
- CustomerModel::find()->with('orders', 'country')->all();
- // 查询客户与他们的订单和订单的发货地址
- CustomerModel::find()->with('orders.address')->all();
- // 查询客户与他们的国家和状态为1的订单
- CustomerModel::find()->with([
- 'orders' => function ($query) {
- $query->andWhere('status = 1');
- },
- 'country',
- ])->all();
注:with中的orders对应getOrders
left join 的用法:
SELECT `user`.* FROM `xx_enewsuser` `user` LEFT JOIN `xx_enewsuser_profile` `profile` ON user.id = profile.user_id WHERE `profile`.`school_id`=1
- $users = User::find()->alias("user")->leftJoin(Profile::tableName() . " as profile", "user.id = profile.user_id")->where(["profile.school_id" => $school_id])->all();
hasmany加条件:
我们还可以在Customer里面定义多个关联。如返回总数大于100的订单。
- class Customer extends \yii\db\ActiveRecord
- {
- public function getBigOrders($threshold = 100)
- {
- return $this->hasMany(Order::className(), ['customer_id' => 'id'])
- ->where('subtotal > :threshold', [':threshold' => $threshold])
- ->orderBy('id');
- }
- }
关联的两种访问方式
如上面的,如果使用
- $customer->bigOrders
将会得到大于100的所有的订单。如果要返回大于200的订单可以这样写
- $orders = $customer->getBigOrders(200)->all();
从上面可以看出访问一个关联的时候有两种方法
如果以函数的方式调用,会返回一个 ActiveQuery 对象($customer->getOrders()->all())
如果以属性的方式调用,会直接返回模型的结果($customer->orders)
给with加过滤条件
- // 查询100个客户的,每个客户的总合大于100的订单
- // 下面的代码会执行sql语句:
- // SELECT * FROM customer LIMIT 100
- // SELECT * FROM order WHERE customer_id IN (1,2,...) AND subtotal>100
- $customers = Customer::find()->limit(100)->with([
- 'orders' => function($query) {
- $query->andWhere('subtotal>100');
- },
- ])->all();
- $model = User::find()->where(['id' => $id])->with([
- "profile" => function($query){
- $query->select("signature,gender,card_no,phone,address,department_id,job_id");
- },
- "profile.department" => function($query){
- $query->select("id,title,leader,sort");
- },
- "profile.job"
- ])->one();
延迟加载和即时加载(又称惰性加载与贪婪加载)
- $customer = Customer::findOne(1);
- // 延迟加载: SELECT * FROM order WHERE customer_id=1 AND subtotal>100
- $orders = $customer->getOrders()->where('subtotal>100')->all();
- // 即时加载: SELECT * FROM customer LIMIT 100
- // SELECT * FROM order WHERE customer_id IN (1,2,...) AND subtotal>100
- $customers = Customer::find()->limit(100)->with([
- 'orders' => function($query) {
- $query->andWhere('subtotal>100');
- },
- ])->all();
常见问题:
1.在查询时加了->select();如下,要加上order_id,即关联的字段(比如:order_id)比如要在select中,否则会报错:undefined index order_id
- // 查询客户与他们的订单和国家
- CustomerModel::find()->select('order_id')->with('orders', 'country')->all();
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值为10,11,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();
- // 根据当前ID 查找parent字段值
- $pid = Menu::findOne(['id'=>$mid])->getAttribute("parent");
- return static::find()->select('title')->where(['id' => $this->pid])->scalar();
- $transaction = Yii::$app->db->beginTransaction();
- try{
- //删除$model中的数据
- $res = $model->deleteAll($cond);
- if(!$res)
- throw new \Exception('操作失败!');
- //删除$model对应的$relation中的数据
- $rt = $relation->deleteAll(['polymeric_id'=>$cond['id']]);
- if(!$rt)
- throw new \Exception('操作失败!');
- //以上执行都成功,则对数据库进行实际执行
- $transaction->commit();
- return Helper::arrayReturn(['status'=>true]);
- }catch (\Exception $e){
- //如果抛出错误则进入catch,先callback,然后捕获错误,返回错误
- $transaction->rollBack();
- return Helper::arrayReturn(['status'=>false,'msg'=>$e->getMessage()]);
- }
- $sql = "SELECT * FROM lime_tokens_".$survey_id." WHERE survey_id = ".$survey_id;
- $participants = \Yii::$app->db_survey->createCommand($sql)->queryAll();
- return $participants;
- // 删除数据表信息(自增不从1开始)
- \Yii::$app
- ->db
- ->createCommand()
- ->delete($tablename)
- ->execute();
- // 清空数据表(自增从1开始)
- Yii::$app->db->createCommand()->truncateTable($tablename)->execute();
- // 指定表名,是否存在于数据库中:
- $table_name = 'lime_tokens_' . $sid;
- $juge = \Yii::$app->db_survey->createCommand("show tables")->queryAll();
- $cun = $this->deep_in_array($table_name, $juge);
- if (!$cun) {
- return $all_partners;
- };
- // 显示数据库中指定表
- $tablename = "lime_tokens_".$survey_id;
- $ta = \Yii::$app->db_survey->createCommand("SHOW TABLES LIKE '" . $tablename . "'")->queryAll();
- //判断二维数组是否存在值
- public function deep_in_array($value, $array) {
- foreach($array as $item) {
- if(!is_array($item)) {
- if ($item == $value) {
- return true;
- } else {
- continue;
- }
- }
- if(in_array($value, $item)) {
- return true;
- } else if($this->deep_in_array($value, $item)) {
- return true;
- }
- }
- return false;
- }
- $sql = 'SELECT count(*) FROM '.UserLinkProject::tableName()." where project_id=".$projectId;
- $participants = \Yii::$app->db->createCommand($sql)->queryScalar();
表前缀
- $id = \Yii::$app->db->createCommand('SELECT `id` FROM {{%menu}} WHERE `name`="插件" AND `parent` IS NULL')->queryScalar();
- $sql = "SELECT * FROM tab WHERE id = :id";
- $db = \Yii::$app->db;
- $command = $db->createCommand($sql, [':id'=>$id]);//方法内部对第二个参数进行PDO参数化,不会导致注入漏洞
- $result = $command->queryAll();
- var_dump($result);
yii2 使用find,update静态方法时,命名空间通过变量名传参使用方式
使用findOne
- $model = call_user_func([$this->entity, 'findOne'], $this->entity_id);
- return $model;
使用updateAll
- // Enewsworkflowitem::updateAll(["is_qf"=>0],["id"=>$entity_id]);
- // Enewsworkflowitem通过变量传参
- $model = call_user_func_array([$entity,"updateAll"],[["is_qf"=>0],["id"=>$entity_id]]);
- return $model;
参考示例说明:
- <?php
- function funa($b,$c)
- {
- echo $b;
- echo $c;
- }
- call_user_func('funa', "111","222");
- call_user_func('funa', "333","444");
- //显示 111 222 333 444
- //这个用法有点像javascript中的call方法
- //第二种是调用类内部的函数
- class a {
- function b()
- {
- $args = func_get_args();
- $num = func_num_args();
- print_r($args);
- echo $num;
- }
- }
- call_user_func(array("a", "b"),"111","222");
- // 看看call_user_func_array函数,它的用法和call_user_func函数比较像,只是参数传入的是数组
- function a($b, $c)
- {
- echo $b;
- echo $c;
- }
- call_user_func_array('a', array("111", "222"));
- //显示 111 222
- // call_user_func_array函数也可以调用类内部的方法的
- Class ClassA
- {
- function bc($b, $c) {
- $bc = $b + $c;
- echo $bc;
- }
- }
- call_user_func_array(array(‘ClassA','bc'), array(“111″, “222″));
- //显示 333
- var $condition = 0;//评论数对比条件
- $user= user::find()->with([
- 'articles' => function ($query) use($condition) {
- $query->where(['>','comment',$condition]);
- }
- ])->all();
多表关联查询,加过滤条件
- return $this->owner->hasMany(Tag::className(), ['id' => 'tag_id'])
- ->viaTable('{{%article_tag}}', ['article_id' => 'id'], function ($query){
- $query->onCondition(['is_zt' => 1]);
- });
- return $this->owner->hasMany(Tag::className(), ['id' => 'tag_id'])
- ->viaTable('{{%article_tag}}', ['article_id' => 'id'])->andWhere(['is_zt'=>0]);
通过关联表查询
主表:cut
标签表:label
关联表:map
cut表:
lable表:
map关联表:
cutModel 中添加方法:
获取该信息关联的多个label
- public function getLabel(){
- // label的id 等于 关联表的 label_id
- // CutMap是关联表,一个cut对应多个label,关联表的cut_id等于 cut表的id
- return $this->hasMany(CutLabel::className(), ['id' => 'label_id'])
- ->viaTable(CutMap::tableName(), ['cut_id' => 'id']);
- }
可以加限制条件
- public function getLabel(){
- // label的id 等于 关联表的 label_id
- // CutMap是关联表,一个cut对应多个label,关联表的cut_id等于 cut表的id
- return $this->hasMany(CutLabel::className(), ['id' => 'label_id'])->andWhere(['status'=>1])
- ->viaTable(CutMap::tableName(), ['cut_id' => 'id']);
- }
视图中使用:
第一种:
- $res = Cut::find()->all();
- foreach ($res as $k => $v){
- echo "<pre>";
- print_r(ArrayHelper::toArray($v));
- print_r(ArrayHelper::toArray($v->label));
- echo "</pre>";
- }
第二种:
- $res = Cut::find()->with("label")->all();
- foreach ($res as $k => $v){
- echo "<pre>";
- print_r(ArrayHelper::toArray($v));
- print_r(ArrayHelper::toArray($v->label));
- echo "</pre>";
- }
有以下sql运行:
- SELECT * FROM `yy_cut`;
- SELECT * FROM `yy_cut_map` WHERE `cut_id`=1;
- SELECT * FROM `yy_cut_label` WHERE `id` IN ('1', '2');
- $role = request()->post("role",null);
- $query = AppMenu::find();
- if($role){
- $query
- ->where(new Expression('FIND_IN_SET(:roe, roe)'))
- ->addParams([':roe' => $role]);
- }
- p($query->createCommand()->getRawSql());
- // SELECT * FROM `xx_app_menu` WHERE FIND_IN_SET('leader', roe)
- $memberIds = ProjectMember::find()->select("user_id")->where(["project_id"=>$model->id])->column();
结果:
)
如果用->asArray()->all()的话,会返回:
)
yii2 查询sql时,字段被强制加反引号`导致SQL执行失败
- $query = (new Query())
- ->select("user_id,true_name,nickname,money,gender,phone,mobile,birthday,referrer_user_id,created_at,FROM_UNIXTIME(created_at,'%Y-%m-%d %H:%I:%S') as created")
- ->from(Profile::tableName())
- ->orderBy("created_at desc");
<pre>SELECT `user_id`, `true_name`, `nickname`, `money`, `gender`, `phone`, `mobile`, `birthday`, `referrer_user_id`, `created_at`, FROM_UNIXTIME(created_at, `'%Y-%m-%d %H:%I:%S')` AS `created` FROM `ningwang_enewsuser_profile` ORDER BY `created_at` DESC</pre>
改成以下new Expression即可:
- $field = "user_id,true_name,nickname,money,gender,phone,mobile,birthday,referrer_user_id,created_at,FROM_UNIXTIME(created_at,'%Y-%m-%d %H:%I:%S') as created";
- $query = (new Query())
- ->select(new Expression($field))
- ->from(Profile::tableName())
- ->orderBy("created_at desc");
完整的sql是:
- SELECT * FROM `block_document` WHERE `id` IN ('9', '1', '2', '21', '3', '4') ORDER BY FIELD (id, 9,1,2,21,3,4)
- // 最新评价
- $documentIdArray = Comment::find()->select("entity_id")->where(["entity"=>\common\modules\document\models\Document::className()])->groupBy("entity_id")->orderBy("created_at desc")->column();
- $documentIds = implode(',' , $documentIdArray);
- $query->andFilterWhere(["in","id",$documentIdArray])
- ->orderBy([new \yii\db\Expression("FIELD (id, $documentIds)")]);
注意一下orderBy里面的数据格式,只能是字符串,以逗号隔开
查询指定用户参与的全部项目下的,所有用户id,过滤掉相同用户id:
- SELECT
- DISTINCT user_id
- FROM
- block_project_user
- WHERE
- project_id IN (
- SELECT
- DISTINCT project_id
- FROM
- block_project_user
- WHERE
- user_id = 28
- )
- // 获取当前用户参与的所有项目下的所有用户id
- $userIds = (new Query())
- ->select('user_id')
- ->distinct('user_id')
- ->from(ProjectUser::tableName())
- ->where(['in', 'project_id',
- (new Query())
- ->select('project_id')
- ->distinct('project_id')
- ->from(ProjectUser::tableName())
- ->where(['in', 'user_id', $user_id])
- ->column()
- ])
- ->column();
- $query->andWhere(["user_id"=>$userIds]);