zoukankan      html  css  js  c++  java
  • TP5.1模型新增

    1.实例化模型对象后赋值并保存

    use appdemomodelAttr;  //,模型
    
    public function mogeng()
    {
    
            // $user           = new Attr;
            // $user->name     = 'thinkphp';
            // $user->color    = 'thinkphp@qq.com';
            //$data= $user->save();


       //在实例化的时候传入数据
        $user = new User([
          'name'  =>  'thinkphp',
          'email' =>  'thinkphp@qq.com'
        ]);
       
        $data= $user->save();
    
    
    //返回值boolean  类型


    }

    2.直接传入数据到save

    use appdemomodelAttr;  //,模型
    
    ublic function mozeng()
        {
    
            $user = new Attr;
            $data=$user->save([
                'name'  =>  'thinkphp',
                'color' =>  'thinkphp@qq.com',
                'create_time'=>time()
            ]);

    //返回值
    boolean  类型
    }

    3.通过外部 post传值给模型,并且希望指定某些字段写入,可以使用:

                $user = new Attr;
            // post数组中只有name和color字段会写入
            $user->allowField(['name','color'])->save($_POST);   
    //返回值boolean  类型


    4.获取自增 id

    $user           = new User;
    $user->name     = 'thinkphp';
    $user->email    = 'thinkphp@qq.com';
    $user->save();
    // 获取自增ID
    echo $user->id;
    这里其实是获取模型的主键,如果你的主键不是id,而是user_id的话,其实获取自增ID就变成这样:
    
    $user           = new User;
    $user->name     = 'thinkphp';
    $user->email    = 'thinkphp@qq.com';
    $user->save();
    // 获取自增ID
    echo $user->user_id;

    5.批量新增

            //批量新增
                $user = new Attr;
                $list = [
                    ['name'=>'thinkphp','color'=>'thinkphp@qq.com','create_time'=>time()],
                    ['name'=>'onethink','color'=>'onethink@qq.com','create_time'=>time()],
                ];
                $data = $user->saveAll($list);

    6.

        $user = Attr::create([
                        'name'  =>  'thinkphp',
                        'color' =>  'thinkphp@qq.com',
                        'create_time'=>time()
                    ], ['name', 'color','create_time']);
                    echo $user->name."<br/>";
                    echo $user->color."<br/>";
                    echo $user->id."<br/>"; // 获取自增ID
                    echo $user->create_time; 
  • 相关阅读:
    python3 crypto winrandom import error
    Flask-Babel 中文支持(zh-CN和zh-Hans-CN)
    pip 安装psycopg的错误
    Aapache status / apache2ctl status 总是403
    为什么你还在用嵌入式的方式来使用mod_wsgi?
    Git中当add错误的时候怎么办?
    Python 内置彩蛋
    本人AI知识体系导航
    本人SW知识体系导航
    SSH密钥对登录的原理和实践
  • 原文地址:https://www.cnblogs.com/79524795-Tian/p/14639648.html
Copyright © 2011-2022 走看看