thinkphp6 模型

1.模型初始化

        在app\common\model 下创建一个User.php文件

2.如果想要使用模型 要在头部引入

use app\common\model\User; //引入模型

3.增 不论是增删改查 fand是根据主键进行查找的

//-----------------------------------
$user  = new User;
$user->name     = 'thinkphp';
$user->number    = 12;
$user->save();

//-------------------------------------
$user = new User;
$user->save([
    'name'  =>  'thinkphp',
    'email' =>  '[email protected]'
]);
//====================================
$user = new User;

// post数组中只有name和email字段会写入

$user->allowField(['name','email'])->save($_POST);
//---------------------------------------

$user = new User;
// 过滤post数组中的非数据表字段数据
$data = Request::only(['name','email']);
$user->save($data);

//----------------------------

$user           = new User;
$user->name     = 'thinkphp';
$user->email    = '[email protected]';
$user->save();
// 获取自增ID
echo $user->id;



ps:->的作用
    是一个对象操作符,用于访问对象的属性和方法。
    这句代码的意思是将'thinkphp'这个值赋给$user对象的name属性

    => 是数组键值对的分隔符号,用于将键和值关联起来创建数组元素。

3.1 批量增加数据

$user = new User;
$list = [
    ['name'=>'thinkphp','email'=>'[email protected]'],
    ['name'=>'onethink','email'=>'[email protected]']
];
$user->saveAll($list);

4.更新数据

$user = User::find(x);
$user->name     = 'thinkphp';
$user->email    = '[email protected]';
$user->save();
//--------------------------------
//复杂情况的数据更新
$user = User::where('status',1)  //找出status为一并且 name为liuchen的数据
	->where('name','liuchen')
	->find();
$user->name     = 'thinkphp';
$user->email    = '[email protected]';
$user->save();
//--------------------------------
$user = User::find(1);
// post数组中只有name和email字段会写入
$data = Request::only(['name','email']);
$user->save($data);
//-------------------------------
$user = new User;
$list = [
    ['id'=>1, 'name'=>'thinkphp', 'email'=>'[email protected]'],
    ['id'=>2, 'name'=>'onethink', 'email'=>'[email protected]']
];
$user->saveAll($list);
这个相当于是把主键为1和2 的都覆盖掉

//把主键id为x的数据取出来之后覆盖原

5.删

$user = User::find(1);
$user->delete();
//----------------------
//删除多条数据
User::destroy([1,2,3]);

6.查

// 取出主键为1的数据
$user = User::find(1);
echo $user->name;

// 使用查询构造器查询满足条件的数据
$user = User::where('name', 'thinkphp')->find();
echo $user->name;

你可能感兴趣的:(php,后端)