TP5.1模型新增
1.实例化模型对象后赋值并保存
use app\demo\model\Attr; //,模型 public function mogeng() { // $user = new Attr; // $user->name = 'thinkphp'; // $user->color = 'thinkphp@qq.com'; //$data= $user->save();
//在实例化的时候传入数据
$user = new User([
'name' => 'thinkphp',
'email' => 'thinkphp@qq.com'
]);
$data= $user->save();
//返回值boolean 类型
}
2.直接传入数据到save
use app\demo\model\Attr; //,模型 ublic function mozeng() { $user = new Attr; $data=$user->save([ 'name' => 'thinkphp', 'color' => 'thinkphp@qq.com', 'create_time'=>time() ]);
//返回值boolean 类型
}
3.通过外部 post传值给模型,并且希望指定某些字段写入,可以使用:
$user = new Attr; // post数组中只有name和color字段会写入 $user->allowField(['name','color'])->save($_POST);
//返回值boolean 类型
4.获取自增 id
$user = new User; $user->name = 'thinkphp'; $user->email = 'thinkphp@qq.com'; $user->save(); // 获取自增ID echo $user->id; 这里其实是获取模型的主键,如果你的主键不是id,而是user_id的话,其实获取自增ID就变成这样: $user = new User; $user->name = 'thinkphp'; $user->email = 'thinkphp@qq.com'; $user->save(); // 获取自增ID echo $user->user_id;
5.批量新增
//批量新增 $user = new Attr; $list = [ ['name'=>'thinkphp','color'=>'thinkphp@qq.com','create_time'=>time()], ['name'=>'onethink','color'=>'onethink@qq.com','create_time'=>time()], ]; $data = $user->saveAll($list);
6.
$user = Attr::create([ 'name' => 'thinkphp', 'color' => 'thinkphp@qq.com', 'create_time'=>time() ], ['name', 'color','create_time']); echo $user->name."<br/>"; echo $user->color."<br/>"; echo $user->id."<br/>"; // 获取自增ID echo $user->create_time;