owladmin 复杂构造语句
xuexi 2026-04-17 15:35:34 发表在:PHP 查看数:8

listQuery() - 构建基础查询 这个 addRelations 方法、category:id,name 到底是什么

/**
 * 构建列表查询
 *
 * @return Builder
 */
public function listQuery()
{
    $query = $this->query();

    // 添加基础条件
    $query->where('status', '!=', 'deleted');

    // 添加权限过滤
    if (!admin_user()->hasRole('admin')) {
        $query->where('created_by', admin_user()->id);
    }

    // 添加关联关系
    $this->addRelations($query, 'list');

    return $query;
}

// 一对多关联:一个扫码记录属于一个分类
public function category() {
    return $this->belongsTo(Category::class);
}

添加关联关系

/**
 * 添加关联关系
 *
 * @param Builder $query
 * @param string $scene 场景: list, detail, edit
 * @return void
 */
public function addRelations($query, string $scene = 'list')
{
    switch ($scene) {
        case 'list':
            // 列表页面需要的关联
            $query->with([
                'category:id,name',
                'user:id,username,avatar',
                'tags:id,name,color'
            ]);
            break;

        case 'detail':
            // 详情页面需要的关联
            $query->with([
                'category',
                'user.profile',
                'tags',
                'comments.user',
                'attachments'
            ]);
            break;

        case 'edit':
            // 编辑页面需要的关联
            $query->with([
                'category:id,name',
                'tags:id,name',
                'permissions:id,name'
            ]);
            break;
    }
}

category:id,name 意思是: 加载分类关联,但只查 id 和 name 两个字段,不查全部字段 目的:提速、省流量

最近访问时间:2026-04-17 22:22:10
知识库:445条鸣谢:TAY  备案号:蜀ICP备2024090044号