新增
新增數(shù)據(jù)有多種方式。
添加一條數(shù)據(jù)
第一種是實(shí)例化模型對象后賦值并保存:
$user = new User;
$user->name = 'thinkphp';
$user->email = '[email protected]';
$user->save();
也可以使用data方法批量賦值:
$user = new User;
$user->data([
'name' => 'thinkphp',
'email' => '[email protected]'
]);
$user->save();
或者直接在實(shí)例化的時(shí)候傳入數(shù)據(jù)
$user = new User([
'name' => 'thinkphp',
'email' => '[email protected]'
]);
$user->save();
如果需要過濾非數(shù)據(jù)表字段的數(shù)據(jù),可以使用:
$user = new User($_POST);
// 過濾post數(shù)組中的非數(shù)據(jù)表字段數(shù)據(jù)
$user->allowField(true)->save();
如果你通過外部提交賦值給模型,并且希望指定某些字段寫入,可以使用:
$user = new User($_POST);
// post數(shù)組中只有name和email字段會(huì)寫入
$user->allowField(['name','email'])->save();
save方法新增數(shù)據(jù)返回的是寫入的記錄數(shù)。
獲取自增ID
如果要獲取新增數(shù)據(jù)的自增ID,可以使用下面的方式:
$user = new User;
$user->name = 'thinkphp';
$user->email = '[email protected]';
$user->save();
// 獲取自增ID
echo $user->id;
注意這里其實(shí)是獲取模型的主鍵,如果你的主鍵不是id,而是user_id的話,其實(shí)獲取自增ID就變成這樣:
$user = new User;
$user->name = 'thinkphp';
$user->email = '[email protected]';
$user->save();
// 獲取自增ID
echo $user->user_id;
注意不要在同一個(gè)實(shí)例里面多次新增數(shù)據(jù),如果確實(shí)需要多次新增,那么可以用下面的方式:
$user = new User;
$user->name = 'thinkphp';
$user->email = '[email protected]';
$user->save();
$user->name = 'onethink';
$user->email = '[email protected]';
// 第二次開始必須使用下面的方式新增
$user->isUpdate(false)->save();
添加多條數(shù)據(jù)
支持批量新增,可以使用:
$user = new User;
$list = [
['name'=>'thinkphp','email'=>'[email protected]'],
['name'=>'onethink','email'=>'[email protected]']
];
$user->saveAll($list);
saveAll方法新增數(shù)據(jù)返回的是包含新增模型(帶自增ID)的數(shù)據(jù)集(數(shù)組)。
V5.0.13+版本開始,saveAll方法的返回類型受模型的resultSetType屬性影響(可能返回?cái)?shù)據(jù)集對象)。
saveAll方法新增數(shù)據(jù)默認(rèn)會(huì)自動(dòng)識(shí)別數(shù)據(jù)是需要新增還是更新操作,當(dāng)數(shù)據(jù)中存在主鍵的時(shí)候會(huì)認(rèn)為是更新操作,如果你需要帶主鍵數(shù)據(jù)批量新增,可以使用下面的方式:
$user = new User;
$list = [
['id'=>1, 'name'=>'thinkphp', 'email'=>'[email protected]'],
['id'=>2, 'name'=>'onethink', 'email'=>'[email protected]'],
];
$user->saveAll($list, false);
靜態(tài)方法
還可以直接靜態(tài)調(diào)用create方法創(chuàng)建并寫入:
$user = User::create([
'name' => 'thinkphp',
'email' => '[email protected]'
]);
echo $user->name;
echo $user->email;
echo $user->id; // 獲取自增ID
和save方法不同的是,create方法返回的是當(dāng)前模型的對象實(shí)例。
助手函數(shù)
系統(tǒng)提供了model助手函數(shù)用于快速實(shí)例化模型,并且使用單例實(shí)現(xiàn),例如:
// 使用model助手函數(shù)實(shí)例化User模型
$user = model('User');
// 模型對象賦值
$user->data([
'name' => 'thinkphp',
'email' => '[email protected]'
]);
$user->save();
或者進(jìn)行批量新增:
$user = model('User');
// 批量新增
$list = [
['name'=>'thinkphp','email'=>'[email protected]'],
['name'=>'onethink','email'=>'[email protected]']
];
$user->saveAll($list);
