模型关联数据显示

未匹配的标注

📖 组件文档请查看 amis ~
🫣 框架论坛




假设你定义了这么一个关联

public function branch()
{
    return $this->belongsTo(Branch::class);
}

如果你连模型关联都没玩明白, 建议先通读并背诵 文档 ~


现在你需要在列表中或者详情中回显

更改 Service 中的查询
// 列表中
public function listQuery()
{
    $model = $this->getModel();

    // 原本的查询长这样
    // return $this->query()->orderByDesc($model->getUpdatedAtColumn());

    // 现在你需要改成这样, 预加载 branch 关联
    return $this->query()->with('branch')->orderByDesc($model->getUpdatedAtColumn());
}

// 详情中
public function getDetail($id)
{
    // 原本的查询长这样
    // return $this->query()->find($id);

    // 现在你需要改成这样, 预加载 branch 关联
    return $this->query()->with('branch')->find($id);
}

更改查询后, 你的数据将从一维变成二维

// 直观一点看

// 原本数据长这样
[
    'id' => 1,
    'name' => '张三',
    'branch_id' => 1,
]

// 现在数据长这样
[
    'id' => 1,
    'name' => '张三',
    'branch_id' => 1,
    'branch' => [
        'id' => 1,
        'name' => '总部',
    ],
]

如果你连数据结构为什么变成这样都有点蒙圈, 建议先通读并背诵 文档 ~


现在你需要在列表中或者详情中回显

// 列表中
// ...
// 你现在可以通过 . 的方式取到多个层级的数据
TableColumn::make()->name('branch.name')->label('所属分公司'),
// ...

// 详情中
// ...
// 你现在可以通过 . 的方式取到多个层级的数据
TextControl::make()->static(true)->name('branch.name')->label('所属分公司'),
// ...


为什么可以这么玩?

这里你需要先了解一下 amis 中的 数据域 概念:
aisuda.bce.baidu.com/amis/zh-CN/do...




😏建议在使用前通读并背诵相关文档: laravelamis ~

常见问题参见 FAQ

本文章首发在 LearnKu.com 网站上。

上一篇 下一篇
《L03 构架 API 服务器》
你将学到如 RESTFul 设计风格、PostMan 的使用、OAuth 流程,JWT 概念及使用 和 API 开发相关的进阶知识。
《L02 从零构建论坛系统》
以构建论坛项目 LaraBBS 为线索,展开对 Laravel 框架的全面学习。应用程序架构思路贴近 Laravel 框架的设计哲学。
讨论数量: 0
发起讨论 只看当前版本


暂无话题~