Thinkphp5.1自定义对象模型继承think\model,model中的db方法:获取当前模型的数据库查询对象,参数:$useBaseQuery 是否调用全局查询范围(或者指定查询范围名称)。
Thinkphp5.1自定义对象模型继承thinkmodel,model中的db方法:获取当前模型的数据库查询对象,参数:$useBaseQuery 是否调用全局查询范围(或者指定查询范围名称)。
thinkmodel类中db方法:
/**
* 获取当前模型的数据库查询对象
* @access public
* @param bool|array $useBaseQuery 是否调用全局查询范围(或者指定查询范围名称)
* @return Query
*/
public function db($useBaseQuery = true)
{
if ($this->queryInstance) {
return $this->queryInstance;
}
$query = $this->buildQuery();
// 软删除
if (property_exists($this, 'withTrashed') && !$this->withTrashed) {
$this->withNoTrashed($query);
}
// 全局作用域
if (true === $useBaseQuery && method_exists($this, 'base')) {
call_user_func_array([$this, 'base'], [ & $query]);
}
$globalScope = is_array($useBaseQuery) && $useBaseQuery ? $useBaseQuery : $this->globalScope;
if ($globalScope && false !== $useBaseQuery) {
$query->scope($globalScope);
}
// 返回当前模型的数据库查询对象
return $query;
}
在自定义模型中打印输出,就可以知道输出的是当前模型数据库查询对象:
<?php
namespace app\index\model;
use think\Model;
class User extends Model
{
// 定义时间戳字段名
protected $createTime = 'createtime';
protected $updateTime = 'updatetime';
// 插入数据
public function insert($data)
{
var_dump($this->db());
}
}
object(think\db\Query)#36 (9) {
["connection":protected]=>
object(think\db\connector\Mysql)#37 (17) {
["builder":protected]=>
object(think\db\builder\Mysql)#38 (8) {
["parser":protected]=>
array(11) {
["parseCompare"]=>
..................................省略..................................
看到这里:thinkdbQuery我们就清楚是thinkphp5.1下的数据库操作类Query,所以还可以直接打印输出,这样打印输出我们发现model 是null,上面的打印可以看出mode就是当前User模型。
var_dump(new \think\db\Query);
简单举例:指定模型,新增记录
<?php
namespace app\index\model;
use think\Model;
use app\index\model\Admin;
class User extends Model
{
// 定义时间戳字段名
protected $createTime = 'createtime';
protected $updateTime = 'updatetime';
// 插入数据
public function insert($data)
{
// 实例化模型
$admin_obj = new \app\index\model\Admin;
/**
* 指定模型
* @access public
* @param Model $admin_obj 模型对象实例
* @return $this
*/
$model_admin = $this->db()->model($admin_obj);
// 查看指定模型对象
var_dump($model_admin->getModel());
// 查看当前模型对象
var_dump($this->getModel());
// 当前模型插入记录
// return $this->save($data);
// 给指定模型新增记录
// return $this->getModel()->insert($data);
}
}
转载注明:
感谢博主,喝杯咖啡~
感谢博主,喝杯咖啡~
还没有人发表评论