tp5使用模型示例

注意模型返回的是对象,可以使用 ->toArray(); 来转换成数组

DB操作返回是数组。

模型直接操作返回是对象。

当我们用 select()进行查询得出的结果 无法toarray的时候,下面的方法就用得上了。

对象类型转换数组

打开 database.php 增加或修改参数
‘resultset_type’ => ‘\think\Collection’,

即可连贯操作
model(‘user’)->select()->toArray()

控制器中

<?php
namespace app\home\controller;

// 模型重命名
use app\home\model\Login as LoginModel;    
use think\Controller;
use think\Session;
use think\Db;
use think\Request;

class login extends controller
{
	public function regpage()
	{
		return $this->fetch('reg');
	}


	// 在这使用模型
	public function reg()
	{
		echo '<pre>';
		$data = $_POST;
		
		// 使用模型
		$login = new LoginModel();
		$result = $login->reg($data);
		
		if($result)
		{
			// die;
			$this->success('注册成功','home/login/index');		// 注册成功,跳到登录页

		}
	 }

}
?>

模型中

<?php
namespace app\home\model;

use think\Model;
use think\Session;
use think\Db;
use think\Request;

class Login extends Model
{
	protected $pk = 'id';
	protected $table = 'tp5_user';
	
	// 增删改查方法
	
	public function insert($data)
	{
        // return $this ->add($data);     // 不能用 add 要用 save
        return $this ->save($data);  
	}

	public function update_my($where,$data)
	{
		$result = $this->where($where)->update($data);   // 或者直接return
		return $result;
        // return $this->where( $where )->save($data);

	}

	public function delete_my($where)
	{
		$result = $this->where($where)->delete();
		return $result;
	}


	public function find($where)
	{
		return $this->where($where)->find();
	}

	public function findall($where)
	{
		// return $this->select();
		return $this->where( $where )->select();
	}

	public function reg($data)
	{
		echo '<pre>';
		// var_dump($data);
		// die;
		$data2 = [
					'username' =>$data['username'],
					'userpass' =>md5($data['password'])
				];

		$where['username'] = $data['username'];
		if($a = $this->find($where))		// 判断用户名是否已注册
		{   

			$this->success('用户名已被注册');   					
		}else if(empty($data['password']))		
		{
	
			$this->success('密码不能为空');
		}else{
		
			$result = $this->insert($data2);
			return $result;
		}	

}


}

?>

控制器中 实验 模型的 增删改查 方法

public function reg()
{
	echo '<pre>';
	$data = $_POST;

	$login = new LoginModel();

	// 试试查询
	// $where['username'] = 'admin';
	// $result = $login->find($where)->toArray();

	// 试试修改
	// $where['id'] = '1';
	// $data222['username'] = 'xiugai';
	
	// $result = $login->update_my($where,$data222);
	
	// 试试删除
	$where['id'] = '1';
	$result = $login->delete_my($where);
	
	
	var_dump($result);
	die;
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值