yii2 使用mongo查询(包含like查询)
基础查询model 类
<?php namespace app\models; use MongoDB\BSON\Regex; use MongoDB\BSON\UTCDateTime; use yii\mongodb\ActiveRecord; /** * Class PlatformPayOrigins * @package app\models */ class MongoDb extends ActiveRecord { /** * @inheritdoc */ public static function getDb() { return \Yii::$app->get('mongodb'); } public static function collectionName() { return 'job_log'; } /** * 获取列表 * @param string $id * @param string $startTime * @param string $endTime * @param int $limit * @param bool $error * @return array|ActiveRecord * @date 2021/3/9 * @time 17:05 */ public function getList($id='',$startTime='',$endTime='',$limit=100,$error = true) { $where = []; if (!empty($id)) { $where['jobId'] = $id; } $items = self::find()->where($where)->select(['_Id','...','...']); if($error){ //包含的数据
//mysql: select * from table where keyword like "%keyword%" if (!empty($where)) { $items->andWhere(['like','keyword','keyword')]); } else { $items->where(['like','keyword','keyword')]); } } if (!empty($startTime)) {
// mysql:select * from table where beginTime >='2021-03-10' if (!empty($where)) { $items->andWhere(['>=', 'beginTime', new UTCDateTime($startTime)]); } else { $items->where(['>=', 'beginTime', new UTCDateTime($startTime)]); } } if (!empty($endTime)) { if (!empty($where)) { $items->andWhere(['<=', 'endTime', new UTCDateTime($endTime)]); } else { $items->where(['<=', 'endTime', new UTCDateTime($endTime)]); } } return $items->limit($limit) ->orderBy('endTime desc') ->asArray() ->all(); } }
使用
$model = new MongoDb(); $model->getList('',$startTime,$endTime);
参考
https://www.yiiframework.com/extension/mongoyii