laravel 數據庫操做

插入數據庫

查詢構造器還提供了 insert 方法用於插入記錄到數據庫中。 insert 方法接收數組形式的字段名和字段值進行插入操做:數組

DB::table('users')->insert(
    ['email' => 'john@example.com', 'votes' => 0]
);

你還能夠在 insert 中傳入一個嵌套數組向表中插入多條記錄。每一個數組表明要插入表中的行:函數

DB::table('users')->insert([
    ['email' => 'taylor@example.com', 'votes' => 0],
    ['email' => 'dayle@example.com', 'votes' => 0]
]);

自增 ID

若是數據表有自增ID,使用 insertGetId 方法來插入記錄並返回ID值:spa

$id = DB::table('users')->insertGetId(
    ['email' => 'john@example.com', 'votes' => 0]
);

更新

固然,除了插入記錄到數據庫中,查詢構造器也可經過 update 方法更新已有的記錄。 update 方法和 insert 方法同樣,接受包含要更新的字段及值的數組。 你能夠經過 where 子句對 update 查詢進行約束: code

DB::table('users')
            ->where('id', 1)
            ->update(['votes' => 1]);

更新 JSON 字段

更新 JSON 字段時,你能夠使用 -> 語法訪問 JSON 對象上相應的值,該操做只能用於支持 JSON 字段類型的數據庫:對象

DB::table('users')
            ->where('id', 1)
            ->update(['options->enabled' => true]);

自增與自減

查詢構造器還爲給定字段的遞增或遞減提供了方便的方法。 此方法提供了一個比手動編寫 update 語句更具表達力且更精練的接口。blog

這兩個方法都至少接收一個參數:須要修改的列。第二個參數是可選的,用於控制列遞增或遞減的量接口

DB::table('users')->increment('votes');

DB::table('users')->increment('votes', 5);

DB::table('users')->decrement('votes');

DB::table('users')->decrement('votes', 5);

你也能夠在操做過程當中指定要更新的字段:事務

DB::table('users')->increment('votes', 1, ['name' => 'John']);

Deletes

查詢構造器也能夠使用 delete 方法從數據表中刪除記錄。在使用 delete 前,可添加 where 子句來約束 delete 語法:rem

DB::table('users')->delete();

DB::table('users')->where('votes', '>', 100)->delete();

若是你須要清空表,你能夠使用 truncate 方法,這將刪除全部行,並重置自增 ID 爲零:

DB::table('users')->truncate();

 

悲觀鎖

查詢構造器也包含一些能夠幫助你在 select 語法上實現 「悲觀鎖定」的函數。若想在查詢中實現一個「共享鎖」,你能夠使用 sharedLock 方法。共享鎖可防止選中的數據列被篡改,直到事務被提交爲止 :

DB::table('users')->where('votes', '>', 100)->sharedLock()->get();

另外,你也能夠使用 lockForUpdate 方法。使用「更新」鎖可避免行被其它共享鎖修改或選取:

DB::table('users')->where('votes', '>', 100)->lockForUpdate()->get();
相關文章
相關標籤/搜索