如何操作数据库?

文档问题 · wqzjd · 于 6年前 发布 · 2192 次阅读

block层操作mysql要调用服务?

共收到 6 条回复
Fecmall#16年前 0 个赞

为了扩展和重构,加入了service层,由service层来访问model层操作数据库,

block不能直接操作model,必须通过services方法来操作数据库,service是公用的。

wqzjd#26年前 0 个赞

不知道我的需求应该调用哪个,如果都行不行就要重写或添加服务

Fecmall#36年前 0 个赞

@wqzjd [#2楼](#comment2) 你是在说梦话,还是在问题? 你不知道,难道我知道?

你要干什么事情,你的需求都不写出来,谁来回答你那个services可以满足你的需求?

如果说梦话,就不要贴上来了。贴自己的记事本上。

想干什么事情,想明白了,一次性贴出来,这不是聊天室。

wqzjd#46年前 0 个赞

比如查询按条件查询某个mysql表

Fecmall#56年前 0 个赞

@wqzjd #4楼 既然你拿不出来具体的例子,我给你举个栗子把,

我如果按照条件批量查询所有的customer

https://github.com/fecshop/yii2_fecshop/blob/master/services/Customer.php

 /**
     * @property $filter|array
     * get  collection by $filter
     * example filter:
     * [
     * 		'numPerPage' 	=> 20,
     * 		'pageNum'		=> 1,
     * 		'orderBy'	=> ['_id' => SORT_DESC, 'sku' => SORT_ASC ],
     * 		'where'			=> [
     *			['>','price','1'],
     *			['<','price','10'],
     * 			['sku' => 'uk10001'],
     * 		],
     * 	'asArray' => true,
     * ]
     * 通过上面的filter数组,得到过滤后的用户数据列表集合。
     */
    protected function actionColl($filter = '')
    {
        $query = $this->_customerModel->find();
        $query = Yii::$service->helper->ar->getCollByFilter($query, $filter);
        //var_dump($query->all());exit;
        return [
            'coll' => $query->all(),
            'count'=> $query->limit(null)->offset(null)->count(),
        ];
    }

如果 $filter 参数的example data 你看不懂,那就只有学习Yii2了

Fecmall#66年前 0 个赞

通过主键查询:

 /**
     * 通过主键,得到customer model
     */
    protected function actionGetByPrimaryKey($val)
    {
        if ($val) {
            $one = $this->_customerModel->findOne($val);
            $primaryKey = $this->getPrimaryKey();
            if ($one[$primaryKey]) {
                return $one;
            } else {
                return new $this->_customerModelName();
            }
        }
    }

进去自己看,函数都有注释

我有一个习惯,帖子都要回复,因此,不要回帖了,自己去看。自己了解。

添加回复 (需要登录)
需要 登录 后方可回复, 如果你还没有账号请点击这里 注册
Your Site Analytics