Thinkphp5 uses the model model to operate the database

Thinkphp standard data table design:

Creation time field: create_time

Update time field: update_time

Delete time field: delete_time 

Type select int, as shown below:

One, create the model folder

Create a new folder named model in the secondary object directory under the application folder, which is at the same level as the corresponding controller and view directories, as shown in the following figure:

If there are multiple modules (such as front-end index, back-end admin), and the operating databases are similar, then the model model can be placed in the common public module, as follows:

Two, create a model model class

1. Create a model object file in the model directory. Generally, the name of the model corresponds to the name of the table, for example:

表名 pre_user       --------------->  模型名 User.php
表名 pre_user_info  --------------->  模型名 UserInfo.php

 2. Define the model model

<?php
namespace app\index\model;
use think\Model;
use think\Db;

class User extends Model{
	/**
     * 定义变量
     * 1.变量名称应与数据表中的字段名相同
     * 2.此处可根据需求省略,因为如果没有,thinkphp会自动在数据表中寻找的对应字段名
     */
	public $username;
	public $password;
}
?>

3. If the data model definition name is inconsistent with the table name, additional definitions and declarations are required, as follows:

<?php
namespace app\index\model;
use think\Model;
use think\Db;

class User extends Model
{
	protected $table = "admin_user";//指定数据表名
    protected $pk = 'id';           //指定主键的字段
}
?>

Three, the method of calling the model model

//导入定义的数据模型类
use \app\index\model\User;

//方法一:
$res = User::get(1);

//方法二:
$user = new User;
$res = $user::get(1);	

//方法三:
use think\Loader;
$user = Loader::model("User");
$res = $user::get(1);

//方法四:
$user = model("User");       
$res = $user::get(1);

Four, query operation

get Get a record

$res = User::get(1);

all get multiple records

1. No transfer of parameters

$result = User::all(); //查询出所有记录 

2. The parameter is n, n is a positive integer 

$result = User::all(1); //查询出id为1的记录

3. The parameters are'n1, n2, n3...'

$result = User::all('7, 8, 9, 10'); //查询出id为7、8、9、10的4条记录 

4. The parameters are [n1, n2, n3...] 

$result = User::all([7, 8, 9, 10]); //查询出id为7、8、9、10的4条记录

find to query an item

 $res = User::where('id','1')->field('name')->find();

 not equal to

->where('id','neq',1)

select multiple queries

$res = User::where('id','1')->field('name')->limit(2)->order('id DESC')->select();

value Query one by field

$res = User::where('id','1')->value('name');

Convert the result into an array

$res = $res->toArray();

Number of queries

//查询总条数
$res = User::count();
//按条件统计条数
$res = User::where('id','>',3)->count();

Five, add operation

1. Use the create() method to add

$res = User::create([
     'name'      => '安阳',
     'age'       => 23,
     'sex'       => 1,
     'password'  => '123456'
 ]);

2. Add data and return the added primary key

$uid=UserModel::create([
     'name'      => '安阳',
     'age'       => 23,
     'sex'       => 1,
     'password'  => '123456'
 ])->id;

You can also use the insertGetId method of the DB class, as follows:

$uid = User::insertGetId([
     'name'      => '安阳',
     'age'       => 23,
     'sex'       => 1,
     'password'  => '123456'
 ]);

3. Add by instantiation method

 

 $user = new User;
 $user->name =  '安阳';
 $user->age =  23;
 $user->save();

4. Filter the inserted field by instantiation, and return the number of inserted rows

 $user = new User;
 $data = [
     'name' => '安阳',
     'age' => 23,
     'email' => '[email protected]'
 ];
 //只有name和age字段会写入
 $res = $user->allowField(['name', 'age'])->save($data);

5. The model uses allowField() to filter data in non-data table fields

//定义模型对象,并传入post数据
$user = new User($_POST);
//过滤post数组中的非数据表字段数据
$user->allowField(true)->save();

6. The model uses allowField() to specify certain fields to write

$user = new User;
// post数组中只有name和email字段会写入
$user->allowField(['name','email'])->save($_POST, ['id' => 1]);

7, batch add use saveAll()

user = new User;
$list = [
    ['name'=>'安阳','email'=>'[email protected]'],
    ['name'=>'小柒','email'=>'[email protected]']
 ];
$user->saveAll($list);

You can also use the insertAll() method of the DB class to return the number of successfully added items 

$res = User::insertAll([
     'name'      => '安阳',
     'age'       => 23,
     'sex'       => 1,
     'password'  => '123456'
 ]);

In addition, other methods of filtering fields:

1. In DB operation, you can use strict to close the field strict inspection

Db::name(‘user’)->strict(false)->insert($data);

2. Use php's unset() method to destroy variables

unset($data[‘file’]);

6. SaveAll adds multiple pieces of data and returns the object list

 $user = new User;
 $data = [
     [
         'name' => '安阳',
         'age' => 20,
         'email' => '[email protected]'
     ],
     [
         'name' => '小柒',
         'age' => 25,
         'email' => '[email protected]'
     ]
 ];
 $res = $user->allowField(['name', 'age'])->saveAll($data);

Six, update operation

1, update returns the number of affected rows

 $res = User::where(['id'=>1])->update(['name'=>'安阳']);

2. setField updates a field individually

User::where('id',1)->setField('name','安阳');

3 、 setInc

//setInc('money',10)表示将money字段加上10
User::where(['id'=>1])->setInc('money', 10);

4、setDec

//setDec('money',10)表示将money字段减去10
User::where(['id'=>1])->setDec('money', 10);

5. Batch update, require the data to contain the primary key, and return to the list of updated objects

$user = new User;
$res = $user->saveAll([
     ['id'=>1, 'name' => '安阳'],
     ['id'=>2, 'name' => '小柒']
 ]);

Seven, delete operation

1. Pass in the primary key and return the number of affected rows

$res = User::destroy(1);

2. Pass in conditions and return the number of affected rows

 $res = User::destroy(['name'=>'安阳']);

3. Conditional delete returns the number of affected rows

 $res = User::where(['id'=>1])->delete();

8. Affairs

1. Automatic control transaction processing

Db::transaction(function(){ 
    Db::table('order')->where(['id'=>1])->delete(); 
	Db::table('user')->where('id'=>1)->setInc('money',10);	
});

2. Manually control transactions

Db::startTrans();//启动事务
try {
    Order::where(['id'=>1])->delete();
	User::where('id'=>1)->setInc('money',10);
	Db::commit();//提交事务
} catch (Exception $e) {
	Db::rollback();	//回滚
}

Nine, the obtainer of the model model

The naming convention of the reader is: ->get + hump naming of attribute name + Attr

<?php
namespace app\index\model;
use think\Model;
class User extends Model
{		    
    //获取器:将性别的012修改为男、女、未知 返回
	public function getSexAttr($val)
	{
		switch ($val) {
            case 1:
                return '男';
            case 2:
                return '女';
            default:
            return '未知';
		}
	}
   //获取器:格式化时间戳后返回
    public function getUpdateTimeAttr($val){
        if(!empty($val)){
			//如果是时间戳,就格式化
			if(!strtotime($val)) {
				return date('Y-m-d H:i:s',$val);
			}else{
				return $val;
			}
        }else{
			return '';
		}
    }
}

Additional explanation: strtotime() parses the date and time description of any English text as a Unix timestamp, and returns a timestamp if it succeeds, otherwise it returns FALSE (before PHP 5.1.0, this function returns -1 when it fails)

Ten, the modifier of the model model

<?php
namespace app\index\model;
use think\Model;
class User extends Model
{
	//修改器
	public function setTimeAttr()
	{
        return time();
	}
    /** 修改器:对密码字段加密之后存储
     * $val  第一个参数是密码
     * $data 第二个参数是添加的数据(可选)
     */
    public function setPasswordAttr($val,$data){
        if($val === '') {
            return $val;
        }else{
            return md5($val.$data['email']);
        }
    }
}

Eleven, automatic completion of the model model

When auto       adds and updates, the auto-completed attribute array
insert      is only added when the auto-completed attribute array
update    is only updated, the auto-completed attribute array

1. Automatic completion 

<?php
namespace app\index\model;
use think\Model;
class User extends Model
{
	//添加和修改时,都会自动完成的字段
    protected $auto = ['addtime'];

    public function setAddtimeAttr(){
        return time();
    }
}

2. Automatically complete when adding data 

<?php
namespace app\index\model;
use think\Model;
class User extends Model
{
	// 新增 自动完成
    protected $insert = ['addtime'];

    public function setAddtimeAttr(){
        return time();
    }
}

3. When the data is updated, it is automatically completed:

<?php
namespace app\index\model;
use think\Model;
class User extends Model
{
	// 更新 自动完成
    protected $update = ['addtime'];

    public function setAddtimeAttr(){
        return time();
    }
}

12. Automatically complete the timestamp

In the database configuration file database.php, there is the following configuration:

//自动写入时间戳字段
'auto_timestamp'  => false,
//如果开启(设置为true),则会自动完成所有表的时间戳,但是不建议这样,只在需要的地方设置更安全。

For example, the timestamp of the user table is automatically completed, which is set in the User model:

<?php
namespace app\index\model;
use think\Model;

class User extends Model{
    //开启自动完成时间戳功能
    protected $autoWriteTimestamp = true;
    //开启后,
    //添加数据时,默认自动完成的字段是:create_time和update_time
    //修改数据时,默认自动完成的字段是:update_time
    
    //如果数据表里不是这两个字段,则会报错。需要进行如下修改:
    protected $createTime = 'addtime';//修改默认的添加时间字段
    protected $updateTime = 'updtime';//修改默认的修改时间字段
    protected $updateTime = false;//当不需要这个字段时设置为false
}

When Thinkphp is updated, the method to automatically update the timestamp of the update_time field:

1. Use update


User::update(['name'='安阳'],['id'=>1]);

The source code of the update method in Thinkphp is as follows:

/**
    * 更新数据
    * @access public
    * @param array      $data  数据数组
    * @param array      $where 更新条件
    * @param array|true $field 允许字段
    * @return $this
    */
   public static function update($data = [], $where = [], $field = null)
   {
       $model = new static();
       if (!empty($field)) {
           $model->allowField($field);
       }
       $result = $model->isUpdate(true)->save($data, $where);
       return $model;
   }

2. Use save

$user=new User;
$user->isUpdate(true)->save(['name'='安阳'],['id'=>1]);

 

 

13. Soft delete

What is soft delete?

When deleting some records, sometimes we need to make a fake deletion, only by modifying the state of a certain field to mark the record as deleted, but in fact, these records still exist in the database. There are still many application scenarios for fake deletion, such as Alipay's collection record. After we delete it on the APP, it will no longer be displayed. Do you think it is really deleted and will not leave any traces? No, no. Deleting Alipay's collection records is just soft deletion. In Alipay's database, these collection records are actually kept. If your collection is suspected of breaking the rules or breaking the law, the police can still pass Alipay's online police Viewed in the background.

1. Turn on soft delete

<?php
namespace app\index\model;
use think\Model;
use traits\model\SoftDelete;//引入软删除的类

class Order extends Model{
    //使用软删除
    //删除时,默认更新的字段是delete_time
    use SoftDelete;
    //如果数据表里不是delete_time这个字段,则会报错。需要进行如下修改:
    protected $deleteTime = 'deltime';
}

2. Soft delete in the controller and return the number of affected rows

 $res = Order::destroy(1);
    

After the deletion is executed, the delete_time field will be updated. If the update_time field is also enabled for automatic completion, the update_time field will also be updated.

3. If soft delete is turned on, you need to delete the data, instead of soft delete, use the following method

//destory()第二个参数传递true
$res = Order::destroy(1,true);

//delete()参数传递true
$orderData = Order::get(1);
$orderData ->delete(true);

4. Query the soft deleted data

$res = Order::withTrashed(true)->find(1);

5. The query only contains data that has been soft deleted

$res = Order::onlyTrashed()->select();

 

Guess you like

Origin blog.csdn.net/qq15577969/article/details/113705451