记录:fastadmin表格数据逗号分隔的id关联展示数据名称并实现搜索
1,在查询后增加显示代码
$fields = [
[
'field'=>'tags_ids', //关联数据字段
'display'=>'tags_name', //附加的字段名称
'primary'=>'id', //关联表主键
'column'=>'tags_name', //关联表中读取需要显示的字段
'model'=>'', //关联模型
'table'=>'fa_litestore_tags' //关联表,关联表和关联模型二选一
]
];
addtion($list,$fields); //list是数组
// addtion($list->items(),$fields); // list是对象
2,增加搜索功能代码
// 特殊搜索处理
$wheres = [];
$filter = json_decode($this->request->get('filter'), true);
$op = json_decode($this->request->get('op'), true);
if(!empty($filter['tags_name'])){
$keyword = $filter['tags_name'];
$tagsIds = implode(',', Db::name('litestore_tags')->where(['tags_name'=>['like',"%$keyword%"]])->column('id'));
$rex = explode(',', $tagsIds);
foreach ($rex as $v){
$wheres[] = ['exp',Db::raw("FIND_IN_SET('$v', tags_ids)")];
}
unset($filter['tags_name']);
unset($op['tags_name']);
}
$this->request->get(['filter'=>json_encode($filter)]);
$this->request->get(['op'=>json_encode($op)]);
3,完整示例
/**
* 查看
*/
public function index()
{
//当前是否为关联查询
$this->relationSearch = true;
//设置过滤方法
$this->request->filter(['strip_tags']);
if ($this->request->isAjax())
{
//如果发送的来源是Selectpage,则转发到Selectpage
if ($this->request->request('keyField'))
{
return $this->selectpage();
}
// 特殊搜索处理
$wheres = [];
$filter = json_decode($this->request->get('filter'), true);
$op = json_decode($this->request->get('op'), true);
if(!empty($filter['tags_name'])){
$keyword = $filter['tags_name'];
$tagsIds = implode(',', Db::name('litestore_tags')->where(['tags_name'=>['like',"%$keyword%"]])->column('id'));
$rex = explode(',', $tagsIds);
foreach ($rex as $v){
$wheres[] = ['exp',Db::raw("FIND_IN_SET('$v', tags_ids)")];
}
unset($filter['tags_name']);
unset($op['tags_name']);
}
$this->request->get(['filter'=>json_encode($filter)]);
$this->request->get(['op'=>json_encode($op)]);
list($where, $sort, $order, $offset, $limit) = $this->buildparams();
$total = $this->model
->with(['category'])
->where($where)
->where($wheres)
->where(['sign'=>'10'])
->where(['is_delete'=>0])
->order($sort, $order)
->count();
$list = $this->model
->with(['category'])
->where($where)
->where($wheres)
->where(['sign'=>'10'])
->where(['is_delete'=>0])
->order($sort, $order)
->limit($offset, $limit)
->select();
$fields = [
[
'field'=>'tags_ids', //关联数据字段
'display'=>'tags_name', //附加的字段名称
'primary'=>'id', //关联表主键
'column'=>'tags_name', //关联表中读取需要显示的字段
'model'=>'', //关联模型
'table'=>'fa_litestore_tags' //关联表,关联表和关联模型二选一
]
];
addtion($list,$fields); //list是数组
// addtion($list->items(),$fields); // list是对象
foreach ($list as &$row) {
$row->getRelation('category')->visible(['name']);
}
$list = collection($list)->toArray();
$result = array("total" => $total, "rows" => $list);
return json($result);
}
return $this->view->fetch();
}
图示: