首页 >社区问答列表 >tp6,在模型中如何调用继承的save方法实现新增?

tp6,在模型中如何调用继承的save方法实现新增?

tp6,定义新增修改方法在模型中
在tp51中,直接使用self::save()表示新增
但是在tp6里面,使用self::save(),报错 ,并不是一个静态方法
Non-static method think\Model::save() should not be called statically
如果使用$this,报错
Using $this when not in object context
那么怎么才能在模型中调用父级的方法实现新增呢?

<?php
namespace app\common\model;
use think\Model;
use think\exception\PDOException;
class Common extends Model
{

    //
    protected static function  init(): void
    {
    }

    /**
     * 添加修改
     **/
    public static function addEdit($data = []){
        $type = isset($data['id']) ? ($data['id']>0 ? 2 : 1) : 1; //?? ?:
        try {
            if($type == 2){ //更新
                $row = self::update($data);
            }else{
                $row = self::save($data);
                //$row = $this->save($data);
            }
            if($row !==false){
                return ['status'=>1,'msg'=>'操作成功', 'data' => '' ];
            }else{
                return ['status'=>0,'msg'=>'操作失败', 'data' => '' ];
            }
        } catch (PDOException $e) {
            return ['status'=>0,'msg'=>$e->getMessage()];
        }
    }


  • 朝游东海
  • 朝游东海    2019-04-24 11:07:321楼

    已解决,自己的问题

    <?php
    namespace app\common\model;
    use think\Model;
    use think\exception\PDOException;
    class Common extends Model
    {
    
        //
        protected static function  init(): void
        {
        }
        /**
         * 添加修改
         **/
        public function addEdit(array $data = []){ //去掉static静态声明
            $type = isset($data['id']) ? ($data['id']>0 ? 2 : 1) : 1; //?? ?:
            try {
                if($type == 2){ //更新
                    $row = self::update($data);
                }else{
                    $row = $this->save($data);
                }
                if($row !==false){
                    return ['status'=>1,'msg'=>'操作成功', 'data' => '' ];
                }else{
                    return ['status'=>0,'msg'=>'操作失败', 'data' => '' ];
                }
            } catch (PDOException $e) {
                return ['status'=>0,'msg'=>$e->getMessage()];
            }
        }

    能调用save()方法了,但是

    又出错了

    array_merge(): Argument #1 is not an array

           $field = array_merge($this->field, $append);

    打印 $this->field

    eq true

    ???

    右键,close all,

    等正式发布以后再来

    +0添加回复

  • 回复