Laravel 数据库交互 - 原生 SQL

2023-01-03 08:40:14 浏览数 (1)

代码语言:javascript复制
        return DB::connection('mysql')->select('SELECT * FROM `article` WHERE `category_id` = ?', [1]);
        return DB::select('SELECT * FROM `article` WHERE `category_id` = ?', [1]);
        #使用命名绑定
        #除了使用 ? 表示参数绑定外,你还可以使用命名绑定的形式来执行一个查询:
        return DB::select('select * from `article` where `id` = :id', ['id' => 2]);

        return DB::insert('insert into `article` (`title`, `content`) values (?, ?)', ['aa', 'aaa']);
        return DB::update('update `article` set `views` = 100 where id = ?', [66]);
        return DB::delete('delete from `article` where id = ?', [66]);

        #自动提交
        return DB::transaction(function () {
            DB::select('select * from `article` where `id` = :id', ['id' => 65]);
            DB::update('update `article` set `views` = 100 where id = ?', [65]);
        });
        #手动提交
        DB::beginTransaction();
        DB::rollBack();
        DB::commit();

        #处理死锁
        DB::transaction(function () {
            DB::update('update users set votes = 1');
            DB::delete('delete from posts');
        }, 5);

https://learnku.com/docs/laravel/9.x/database/12245

0 人点赞