1、1对1关联查询

https://doc.fastadmin.net/doc/controller.html#toc-4

比如这个文章属于哪个分类,是一对一的关系,如何显示呢?很简单。
首先,表fa_article要有一个fa_category的外键字段。

1.1、首先我们需要在当前控制器中添加以下属性

  1. protected $relationSearch = true;

1.2、然后我们修改控制器的index方法,代码如下:
注意:我们要去复制基类的方法然后修改!!!基类在 app\admin\library\traits 路径下的 Backend 类

  1. /**
  2. * 查看
  3. */
  4. public function index()
  5. {
  6. //设置过滤方法
  7. $this->request->filter(['strip_tags', 'trim']);
  8. if ($this->request->isAjax()) {
  9. //如果发送的来源是Selectpage,则转发到Selectpage
  10. if ($this->request->request('keyField')) {
  11. return $this->selectpage();
  12. }
  13. list($where, $sort, $order, $offset, $limit) = $this->buildparams();
  14. $list = $this->model
  15. ->with(["xx"]) //加上这个,xx是自定义的名字,和Model类的方法一一对应。
  16. ->where($where)
  17. ->order($sort, $order)
  18. ->paginate($limit);
  19. $result = array("total" => $list->total(), "rows" => $list->items());
  20. return json($result);
  21. }
  22. return $this->view->fetch();
  23. }
  1. public function xx()
  2. {
  3. // 第一个参数是 对应的实体类的Model,第二个是外键字段
  4. return $this->belongsTo('app\common\model\Category', 'article_category_id')->setEagerlyType(0);
  5. }

前台如何显示?找到对应的js文件,修改表格参数

  1. {field: 'xx.name', title: "分类名字"},

2、显示自定义的字段

但是,这个会出现这个类的所有的字段,这并不是我们所需要的,这个时候,需要显示自定义的字段。

1、首选需要将原来的字段对象给删除掉

  1. // 重点!!!,遍历移除掉这个属性
  2. $items = $list->items();
  3. foreach ($items as $key => $val ){
  4. unset($val['xx']);
  5. }

2、绑定指定的字段

  1. public function category()
  2. {
  3. // 第一个参数是 对应的实体类的Model,第二个是外键字段 .bind("name","nickname");
  4. return $this->belongsTo('app\common\model\Category', 'article_category_id')->setEagerlyType(0)->bind('nickname');
  5. }

3、自定义搜索

在 controller中加上这个属性

  1. /**
  2. * 快速搜索时执行查找的字段
  3. */
  4. protected $searchFields = ['id','category.name'];