TP6模型原理与基本操作教程_php菜鸟技术天地-CSDN博客

查询:

$rsec = ChatCard::where('uid',$uid)->find();
//查询表有后缀
$rsec = ChatCard::suffix($setSuffix_7d)->where('uid',$uid)->find();
//输出SQL
$rsec = ChatCard::suffix($setSuffix_7d)->where('uid',$uid)->fetchSql(true)->find();

注意:save()方法添加与更新

更改保存默认数据库连接,把数据保存到其它库中
$Guestbook->connect('ente_cold')->save($postdata);

保存到默念连接数据库中
$Guestbook->save($postdata);

1.不用判断添加、更新是否成功,有错误会自动抛出

下面是错误写法:

//错误写法
$Guestbook->save($postdata);
if($Guestbook->isEmpty()){
	throw new \Exception('保存失败!');
}

2.添加数据:默认只会写入数据表已有的字段

默认只会写入数据表已有的字段,如果你通过外部提交赋值给模型,并且希望指定某些字段写入,可以使用:

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

最佳的建议是模型数据赋值之前就进行数据过滤,例如:

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

3.不要在同一个实例里面多次新增数据,如果确实需要多次新增,可以使用后面的静态方法处理。

静态方法

还可以直接静态调用create方法创建并写入:

$user = User::create([
    'name'  =>  'thinkphp',
    'email' =>  'thinkphp@qq.com'
]);
echo $user->name;
echo $user->email;
echo $user->id; // 获取自增ID

save方法不同的是,create方法返回的是当前模型的对象实例。

create方法默认会过滤不是数据表的字段信息,可以在第二个参数可以传入允许写入的字段列表,例如:

// 只允许写入name和email字段的数据
$user = User::create([
    'name'  =>  'thinkphp',
    'email' =>  'thinkphp@qq.com'
], ['name', 'email']);
echo $user->name;
echo $user->email;
echo $user->id; // 获取自增ID

4.save方法更新数据,只会更新变化的数据,对于没有变化的数据是不会进行重新更新的。如果你需要强制更新数据,可以使用下面的方法

$user = User::find(1);
$user->name     = 'thinkphp';
$user->email    = 'thinkphp@qq.com';
$user->force()->save();

5.自动识别

我们已经看到,模型的新增和更新方法都是save方法,系统有一套默认的规则来识别当前的数据需要更新还是新增。

  • 实例化模型后调用save方法表示新增;
  • 查询数据后调用save方法表示更新;

不要在一个模型实例里面做多次更新,会导致部分重复数据不再更新,正确的方式应该是先查询后更新或者使用模型类的update方法更新

不要调用save方法进行多次数据写入。

实际例子:

1.分布式数据库插入多表数据,有事务需要回滚

调用:

//引用
use app\services\table\model\Guestbook;

//静态调用
$returnData = Guestbook::saveGuestbook($postdata);

表对应模型文件代码:

<?php
namespace app\services\table\model;
use think\Model;
use think\facade\Db;
use app\services\table\validate\GuestbookValidate;

class Guestbook extends Model
{
    protected $name = 'guestbook'; //表名 
    protected $connection = 'enterprise_cold';//数据库的连接


    protected $autoWriteTimestamp = 'int';//开启自动写入创建和更新的时间戳 不设置下面填入字段,默认会自动写入create_time和update_time两个字段的值 默认为整型(int
    protected $createTime = 'time';//指定time字段自动填入 
    protected $updateTime = 'utime';//指定utime字段自动填入

    // 设置字段信息
    protected $schema = [
        'id'          => 'int',
        'uid'          => 'bigint',//(唯一:前端用户取得电脑MAC转为十制进数字)
        'enterprise_id'        => 'int',
        'phone'        => 'string',
        'username'      => 'string',
        'content'       => 'string',
        'gid' => 'int',
        'sid' => 'int',
        'wx' => 'string',
        'email' => 'string',
        'qq' => 'int',
        'url' => 'string',
        'ip' => 'string',
        'type' => 'int',
        'hide' => 'int',
        'deleted' => 'int',
        'deleted_time' => 'int',
        'deleted_userid' => 'int',
        'time' => 'int',
    ];

	/**
	* @name 保存访客提交过来的留言
	* @method Model
	* @date 2021-11-19
    * @param 1 $postdata arr/必填 提交数组
	* @ruturn array
	*/
	static public function saveGuestbook(array $postdata)
	{
		Db::connect('enterprise_cold')->startTrans();
		Db::connect('enterprise_heat')->startTrans();
		try {

			$postdata['enterprise_id'] = !empty($postdata['eid'])?$postdata['eid']:0;
			
			validate(GuestbookValidate::class)->scene('onlineserviceApi_tel')->check($postdata);

			// $eid = !empty($postdata['enterprise_id'])?$postdata['enterprise_id']:0;
			$enterpriseData = numberEncodeDecodeHashids('enterprise',$postdata['enterprise_id'],1);//解密
			if($enterpriseData['code']!=200){
				throw new \Exception("非法提交,互联网不是法外之地,请慎重!");
			}
            //客服分组ID
            if(!empty($postdata['gid'])){
                $enterpriseData = numberEncodeDecodeHashids('onlineservice_group',$postdata['gid'],1);//解密
                if($enterpriseData['code']!=200){
                    throw new \Exception("非法提交,互联网不是法外之地,请慎重!");
                }
            }
            //客服ID
            if(!empty($postdata['sid'])){
                $enterpriseData = numberEncodeDecodeHashids('enterprise_userid',$postdata['sid'],1);//解密
                if($enterpriseData['code']!=200){
                    throw new \Exception("非法提交,互联网不是法外之地,请慎重!");
                }
            }

			$postdata['enterprise_id'] = $enterpriseData['data'][0];

			//1.7天表、1个月表
			self::connect('enterprise_heat')->setSuffix('_7d')->save($postdata);//7天表
			self::connect('enterprise_heat')->setSuffix('_1m')->save($postdata);//1个月表

			//2.今年表 以前表
			(new static())->setSuffix('_1y')->save($postdata);//今年表
			(new static())->save($postdata);//以前表(所有数据表)

		    $code=200;$msg="成功";
			Db::connect('enterprise_cold')->commit();
			Db::connect('enterprise_heat')->commit();
		} catch (\Exception $e) {
			Db::connect('enterprise_cold')->rollback();
			Db::connect('enterprise_heat')->rollback();
			$code=-200;$msg=$e->getMessage();
		}
        return ['code' => $code,'msg' =>$msg];

	}

}

 取得自增ID

            $rs = self::connect('chat_heat')->setSuffix($setSuffix_7d);
            $rs->save($postdata);//7天表
            dump($rs->id);die;

2.单库单表插入数据(有事就启用)

调用:

//引用
use app\services\table\model\Guestbook;

//动态调用 要实例化
$TaskLog =new TaskLog();
$returnData = $TaskLog ->saveGuestbook($postdata);

表对应模型文件代码:

<?php
namespace app\services\table\model;
use think\Model;
use think\facade\Db;
use app\services\table\validate\TaskLogValidate;

/**
* @name 任务日志
* @method Model/POST/GET/
* @date 2021-12-01
*/
class TaskLog extends Model
{
    protected $name = 'task_log'; //表名 
    protected $connection = 'log';//数据库的连接


    protected $autoWriteTimestamp = 'int';
    protected $createTime = 'time';
    // protected $updateTime = 'utime';

    // 设置字段信息
    protected $schema = [
        'id'          => 'int',
        'user_id'          => 'int',
        'enterprise_id'        => 'int',
        'title'        => 'string',
        'data'      => 'string',
        'content'       => 'string',
        'starttime' => 'int',
        'endtime' => 'int',
        'url' => 'string',
        'state' => 'int',
        'url' => 'string',
        'type' => 'int',
        'mold' => 'int',
        'delay' => 'int',
        'time' => 'int',
    ];


	/**
	* @name 保存访客提交过来的留言
	* @method Model
	* @date 2021-11-19
    * @param 1 $postdata arr/必填 提交数组
	* @ruturn array
	*/
    public function DataSave(array $postdata)
	{
		// Db::connect($this->connection)->startTrans();//有回滚就启用
		try {

            
			// if(empty($postdata)){
            //     throw new \Exception("提交数据为空!");
            // }
			$postdata['enterprise_id'] = !empty($postdata['eid'])?$postdata['eid']:0;
			
			validate(TaskLogValidate::class)->check($postdata);

            if(!empty($postdata['enterprise_id'])){
                $enterpriseData = numberEncodeDecodeHashids('enterprise',$postdata['enterprise_id'],1);//解密
                if($enterpriseData['code']!=200){
                    throw new \Exception("非法提交,互联网不是法外之地,请慎重!");
                }
                $postdata['enterprise_id'] = $enterpriseData['data'][0];
            }

			$this->save($postdata);//以前表(所有数据表)

		    $code=200;$msg="成功";
			// Db::connect($this->connection)->commit();
		} catch (\Exception $e) {
			// Db::connect($this->connection)->rollback();
			$code=-200;$msg=$e->getMessage();
		}
        return ['code' => $code,'msg' =>$msg];

	}

}

官网教程:

新增 · ThinkPHP6.0完全开发手册 · 看云

更新 · ThinkPHP6.0完全开发手册 · 看云

Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐