这里需对表fa_setting_employees进行关联,yewu为本表字段,employee_num为fa_setting_employees的字段,通过yewu与employee_num进行关联,需要查询fa_setting_employees表中的employee_name字段
一、在模型中进行关联
位置:application/admin/model/pim/Test.php
通过belongsTo进行关联
①'app\admin\model\setting\Employees':表示关联位置
②'yewu':表示本表的关联字段
③'employee_num':表示关联表的关联字段
表示从FastAdmin应用程序中的当前模型发出一个“yewu”作为外键,关联到“app\admin\model\setting\Employees”模型中的“employee_num”字段,并且使用LEFT JOIN类型查询,同时设置Eagerly Type为0,以确保从当前模型进行懒加载查询
public function employees()//yewu为第一张表的字段,employee_num为第二张表的字段
{
return $this->belongsTo('app\admin\model\setting\Employees', 'yewu', 'employee_num', [], 'LEFT')->setEagerlyType(0);
}
二、对控制器写入关联方法
位置:application/admin/controller/pim/Test.php
详细代码详解部分可参考:https://blog.csdn.net/weixin_46001736/article/details/128615011?spm=1001.2014.3001.5501
/**
* 查看
*/
public function index()
{
//当前是否为关联查询
$this->relationSearch = true;
//设置过滤方法
$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(['employees'])//关联的表
->where($where)
->order($sort, $order)
->paginate($limit);
foreach ($list as $row) {
//显示关联表中的employee_name字段
$row->getRelation('employees')->visible(['employee_name']);
}
$result = array("total" => $list->total(), "rows" => $list->items());
return json($result);
}
return $this->view->fetch();
}
三、在js中进行关联数据展示
位置:public/assets/js/backend/pim/test.js
{field: 'employees.employee_name', title: __('关联id')},
在js中的columns中加入需要展示的字段
employees.employee_name:表示在employees表中引用employee_name字段