codecamp

新增,更新,删除

要从模型新增一条数据到数据库,只要建立一个模型实例并调用 save 方法即可。

储存新的模型数据

$user = new User;
$user->name = 'John';
$user->save();

注意: 通常 Eloquent 模型主键值会自动递增。但是您若想自定义主键,将 incrementing 属性设成 false 。

也可以使用 create 方法存入新的模型数据,新增完后会返回新增的模型实例。但是在新增前,需要先在模型类里设定好 fillableguarded 属性,因为 Eloquent 默认会防止批量赋值。

在新模型数据被储存或新增后,若模型有自动递增主键,可以从对象取得 id 属性值:

$insertedId = $user->id;

在模型里设定 Guarded 属性

class User extends Model {
    protected $guarded = ['id', 'account_id'];
}

使用模型的 Create 方法

// 在数据库中建立一个新的用户...
$user = User::create(['name' => 'John']);
// 以属性找用户,若没有则新增并取得新的实例...
$user = User::firstOrCreate(['name' => 'John']);
// 以属性找用户,若没有则建立新的实例...
$user = User::firstOrNew(['name' => 'John']);

更新取出的模型

要更新模型,可以取出它,更改属性值,然后使用 save 方法:

$user = User::find(1);
$user->email = 'john@foo.com';
$user->save();

储存模型和关联数据

有时您可能不只想要储存模型本身,也想要储存关联的数据。您可以使用 push 方法达到目的:

$user->push();

您可以结合查询语句,批次更新模型:

$affectedRows = User::where('votes', '>', 100)->update(['status' => 2]);

注意: 若使用 Eloquent 查询构造器批次更新模型,则不会触发模型事件。

删除模型

要删除模型,只要使用实例调用 delete 方法:

$user = User::find(1);
$user->delete();

按主键值删除模型

User::destroy(1);
User::destroy([1, 2, 3]);
User::destroy(1, 2, 3);

当然,您也可以结合查询语句批次删除模型:

$affectedRows = User::where('votes', '>', 100)->delete();

只更新模型的时间戳

如果您只想要更新模型的时间戳,您可以使用 touch 方法:

$user->touch();
批量赋值
软删除
温馨提示
下载编程狮App,免费阅读超1000+编程语言教程
取消
确定
目录

环境配置

系统服务

哈希

关闭

MIP.setData({ 'pageTheme' : getCookie('pageTheme') || {'day':true, 'night':false}, 'pageFontSize' : getCookie('pageFontSize') || 20 }); MIP.watch('pageTheme', function(newValue){ setCookie('pageTheme', JSON.stringify(newValue)) }); MIP.watch('pageFontSize', function(newValue){ setCookie('pageFontSize', newValue) }); function setCookie(name, value){ var days = 1; var exp = new Date(); exp.setTime(exp.getTime() + days*24*60*60*1000); document.cookie = name + '=' + value + ';expires=' + exp.toUTCString(); } function getCookie(name){ var reg = new RegExp('(^| )' + name + '=([^;]*)(;|$)'); return document.cookie.match(reg) ? JSON.parse(document.cookie.match(reg)[2]) : null; }