1、1对1关联查询
https://doc.fastadmin.net/doc/controller.html#toc-4
比如这个文章属于哪个分类,是一对一的关系,如何显示呢?很简单。
首先,表fa_article要有一个fa_category的外键字段。
1.1、首先我们需要在当前控制器中添加以下属性
protected $relationSearch = true;
1.2、然后我们修改控制器的index方法,代码如下:
注意:我们要去复制基类的方法然后修改!!!基类在 app\admin\library\traits 路径下的 Backend 类
/**
* 查看
*/
public function index()
{
//设置过滤方法
$this->request->filter(['strip_tags', 'trim']);
if ($this->request->isAjax()) {
//如果发送的来源是Selectpage,则转发到Selectpage
if ($this->request->request('keyField')) {
return $this->selectpage();
}
list($where, $sort, $order, $offset, $limit) = $this->buildparams();
$list = $this->model
->with(["xx"]) //加上这个,xx是自定义的名字,和Model类的方法一一对应。
->where($where)
->order($sort, $order)
->paginate($limit);
$result = array("total" => $list->total(), "rows" => $list->items());
return json($result);
}
return $this->view->fetch();
}
public function xx()
{
// 第一个参数是 对应的实体类的Model,第二个是外键字段
return $this->belongsTo('app\common\model\Category', 'article_category_id')->setEagerlyType(0);
}
前台如何显示?找到对应的js文件,修改表格参数
{field: 'xx.name', title: "分类名字"},
2、显示自定义的字段
但是,这个会出现这个类的所有的字段,这并不是我们所需要的,这个时候,需要显示自定义的字段。
1、首选需要将原来的字段对象给删除掉
// 重点!!!,遍历移除掉这个属性
$items = $list->items();
foreach ($items as $key => $val ){
unset($val['xx']);
}
2、绑定指定的字段
public function category()
{
// 第一个参数是 对应的实体类的Model,第二个是外键字段 .bind("name","nickname");
return $this->belongsTo('app\common\model\Category', 'article_category_id')->setEagerlyType(0)->bind('nickname');
}
3、自定义搜索
在 controller中加上这个属性
/**
* 快速搜索时执行查找的字段
*/
protected $searchFields = ['id','category.name'];