控制器写法
添加类属性,是否是关联查询
protected $relationSearch = true;
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
//关联admin表
->with(['admin'=>function($admin){
$admin->withField('nickname'); //username为主表关联name表的字段
}])
->where($where)
->order($sort, $order)
->paginate($limit);
$result = array("total" => $list->total(), "rows" => $list->items());
return json($result);
}
return $this->view->fetch();
}
模型写法
public function admin()
{
//belongsTo 第一个参数为要关联的模型, 第二个参数为用哪个字段关联模型
return $this->belongsTo('app\admin\model\Admin', 'admin_id')->setEagerlyType(0);
}