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