YII2.0 查询生成器-数据库访问

来源:互联网 发布:赛鸽登记软件 编辑:程序博客网 时间:2024/05/16 14:24
<?phpnamespace app\controllers;use yii;use yii\web\Controller;use yii\db\Query;class DataController extends Controller{    public function actionIndex()    {        // 数据查询        // 使用表前缀查询{{%table}}//        $result = Yii::$app->getDb()->createCommand("SELECT COUNT([[id]]) FROM {{%user}}")->queryScalar();        // 查询多条语句        $result = Yii::$app->getDb()->createCommand('select * from {{user}}')->queryAll();        // 查询一条语句        $id = 'xxx';        $result2 = Yii::$app->getDb()->createCommand("select * from  {{user}} where id  =:id")->bindValue('id', $id)->queryOne();        var_dump($result);die;    }    public function actionInsert()    {        // 单条数据插入 成功返回1        Yii::$app->getDb()->createCommand()->insert('user', [            'name' => 'yanglu',            'email' => '619508448@qq.com',            'address' => '广东'        ])->execute();    }    //批量插入数据    public function actionBatch()    {        $res = Yii::$app->getDb()->createCommand()->dropTable('user1')->execute();        // 成功返回插入记录的数量和        $result = Yii::$app->getDb()->createCommand()->batchInsert('user',['name', 'email', 'address'], [            ['张三, "6194@qq.com", '深圳'],            ['李四', "4170@qq.com", '深圳'],            ['王五', "542@qq,com", '北京'],        ])->execute();    }    // 查询构建器    public function actionSelect()    {        $query = new \yii\db\Query();        $rows = $query->select('id as userId, name, email, address as addr')->from('user')->where(['name' => 'name'])->limit(10)->all();        $rows2 = $query->select(['user.id as user_id', 'user.name', 'user.email', 'user.address as addr'])->from('user')->where(['name' => '杨利'])->limit(10)->all();        $rows3 = $query->select('id, name, email')->from('user')->where(['like', 'name', 'xxx'])->limit(100)->all();        $rows4 = (new Query())->select('id')->from('user');        $rows5 = $query->from('user')->where(['id' => $rows4])->all();        $rows6 = (new Query())->from('user')->where(['and', 'name="name..."',  'email = "61950844@qq.com"', 'address="xxxx"'])->orderBy('id desc')->all();        $rows7 = (new Query())->from('user')->groupBy('id')->indexBy(function ($row){            return $row['id'] . '_' . $row['name'];        })->orderBy('id desc');        foreach ($rows7->batch() as $batch) {            var_dump($batch);die;        }                var_dump($rows7);    }}
原创粉丝点击