注意模型返回的是对象,可以使用 ->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;
}