{{wikiTitle}}
Dao
复制链接
编辑文档
Dao
-
Dao定义
目录位于
\app\common\dao
具体dao下在分块,根据具体逻辑功能不同划分
dao位于数据模型model层与逻辑处理层repository之间,处理每个特定逻辑数据库操作或有共性的查询、操作等
每一个dao对应一个model,比如在\app\common\model下存在User模型,那么在\app\dao下必然存在一个UserDao,必需继承baseDao并实现getModel方法,关联一个model类
protected function getModel(): string
{
return User::class;
}
一个dao操作一个model类,model也只能通过这个dao被使用,不允许跨dao调用以及夸层级调用model
完整定义一个dao
<?php
namespace app\dao\user;
use app\dao\BaseDao;
use app\model\user\User;
/**
* 用户
* Class UserDao
* @package app\dao\user
*/
class UserDao extends BaseDao
{
protected function getModel(): string
{
return User::class;
}
//公共查询列表
public function search(array $where)
{
return $this->getModel()->getDb()->where('id',$where['id']);
}
}
-
使用
repository->dao->model 都是单一对应 dao必需在对应的repository中调用,不能被其他repository或者dao调用 比如:UserDao 必然只能被UserServices 使用 repository中注入对应dao
public function __construct(UserDao $dao) { $this->dao = $dao; }
在repository中使用
$this->dao
就可以直接调用dao中定义的查询或者增删改差逻辑,比如:
$this->dao->search(['is_del'=>0]);
repository完整使用:
namespace app\common\repositories\user;
use app\common\dao\user\UserDao;
class UserRepository extends BaseRepository { protected $dao; public function __construct(UserDao $dao) { $this->dao = $dao; }
public function search(array $where, int $page, int $limit)
{
$query = $this->dao->search($where);
$list = $query->page($page,$limit)->select();
$count =$query->count();
return compact('count','list');
}
}
* ## baseDao介绍
baseDao中内置了一些常用查询、聚合、添加、修改方法,如下:
* @ get(int $id) 获取一条数据(主键)
返回`find()`查询结果集对象
* @ getWhere(array $where, string $field = '*', array $with = [])获取一条数据(多条件)
返回`find()`查询结果集对象
* @ selectWhere(array $where, string $field = '*')获取一条数据(多条件)
返回`select()`查询结果集对象
* @ getWith(int $id, array $with)获取一条数据(关联查询)
返回`find()`结果,查询结果集对象
* @ update($id, array $data) 修改数据
返回`update()`结果,影响数据条数
* @ updates($id,s array $data) 修改数据(多条数据)
返回`update()`结果,影响数据条数
* @ fieldExists($map, string $field = '') 查询一条数据是否存在
返回`true|false`
* @ getWhereCount(array $where = []) 获取某些条件总数(复杂条件嵌套,可以是二位数组)
返回`count()`统计条数
* @ findOrCreate(array $where) 查询某个数据是否存在,如果不存在就创建这条数据
返回`create()`结果,当前模型对象实例
* @ delete($id, ?string $key = null) 删除
返回`delete()`结果
* @ create(array $data) 保存数据
返回`create()`结果,当前模型对象实例
* @ insertAll(array $data) 批量保存数据
返回`insertAll()`结果,添加数据条数
* @ getSearch(array $where) 搜索器,传入where条件,在model中定义搜索器就可查询
返回`select()`结果
* @ incField(int $id, string $field , $num = 1) 条件自增
返回`update()`结果
* @ decField(int $id, string $field , $num = 1)条件自减
返回`update()`结果
评论({{cateWiki.comment_num}})
最新
最早
{{cateWiki.page_view_num}}人看过该文档
评论(0)
最新
最早
1027人看过
登录/注册
即可发表评论
{{item.user ? item.user.nickname : ''}}
(自评)
{{item.content}}
搜索结果
为您找到{{wikiCount}}条结果
{{item.page_view_num}}
{{item.like ? item.like.like_num : 0}}
{{item.comment ? item.comment.comment_num : 0}}
位置:
{{path.name}}
{{(i+1) == getCataloguePathData(item.catalogue).length ? '':'/'}}
