用户Model创建
php artisan make:model User
Laravel-增删改查
1、数据添加
路由/app/http/routes.php
Route::get('/test',function(){
$user=new App\User();
$user->userAdd();
return $user->userRead();
});
/app/User.php Model
public function userAdd()
{
//方法1 字段作为数组形式填充到表
$user_data=['username'=>'yuan','age'=>22];
$this->fill($user_data);
//方法2 单个字段变量保存到表
$this->username='caoyuan';
$this->age=18;
$this->save();
}
2、关闭时间戮
/app/User.php
public $timestamps=false; 默认为 true,False关闭
3、get或or默认返回所有的
public function userTest()
{
return $this->all();
}
4、数据修改
路由/app/http/routes.php
Route::get('/test',function(){
$user=new App\User();
//$user->userAdd();
$user->userUpdate();
return $user->userRead();
});
单个数据修改
/app/User.php
public function userUpdate(){
$user=$this->find(8);
$user->username="laobai";
$user->age=80;
$user->save();
}
批量修改数据
public function userUpdate(){
$users=$this->where('user_id','<','8'); //user_id小于8的
$users->update(['username'=>'dabai','age'=>60]);
//update返回的是集合数据自带保存数据
// $users->save();
}
5、删除数据
路由/app/http/routes.php
Route::get('/test',function(){
$user=new App\User();
$user->userDelete();
return $user->userRead();
});
/app/User.php
public function userDelete()
{
$user=$this->find(8);
$user->delete();
}