tp5中的查询构造器、链式操作、两种事务操作总结

use/think/Db;

/******** 查询构造器 *********/
        // 插入记录
//        Db::table('sb_ad')->insert(['ad_name' => 6, 'ad_content' => 'thinkphp', 'status' => 1]);
        // 更新记录
//        Db::table('sb_ad')
//            ->where('ad_id', 2)
//            ->update(['ad_name' => "hello"]);

        // 查询数据
//        $list = Db::table('sb_ad')
//            ->where('ad_id', 2)
//            ->select();
//      dump($list);
        // 删除数据
//        Db::table('sb_ad')
//            ->where('ad_id', 2)
//            ->delete();       
       
      // 插入记录
//      Db::name('ad')->insert(['ad_name' => 2, 'ad_content' => '77777777777777']); 
       
       /****链式操作****/
        // 查询十个满足条件的数据 并按照role_id倒序排列
//        $list = Db::name('auth_access')
//                ->field('role_id,rule_name')
//                ->order('role_id', 'desc')
//                ->limit(10)
//                ->select();
//        print_r($list);
        
       //事务支持 在Mysql数据库中请设置表类型为InnoDB
       //把需要执行的事务操作封装到闭包里面即可自动完成事务

//        Db::transaction(function () {
//            Db::table('sb_ad')->where('ad_id', 1)->select();
//            Db::table('sb_add')->insert(['ad_name' => 10, 'ad_content' => 'thinkphp', 'status' => 1]);
//        });    

       // 手动控制事务的提交
        // 启动事务
       Db::startTrans();
       try {
            Db::table('sb_ad')
                ->insert(['ad_namea' => 13, 'ad_content' => 'thinkphp', 'status' => 1]);
           Db::table('sb_ad')
               ->insert(['ad_name' => 11, 'ad_content' => 'thinkphp', 'status' => 1]);
           // 提交事务
           echo 'try';
           Db::commit();
       } catch (\Exception $e) {
           // 回滚事务
           echo 'catch';
           Db::rollback();
       }       
       
       
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容