Laravel 数据库交互 - 原生 SQL

发布于 2023-01-02 13:55 阅读 766
        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

广而告之,我的新作品《语音助手》上架Google Play了,欢迎下载体验