application\admin\controller\qjzj\Place.php(不变)
add.html文件代码
application\admin\view\qjzj\house\add.html(添加)
注意:一般在CRUD关联自动生成的代码,添加和编辑选择时选择显示的是数据库中name的值,如果想显示关联的其他值可以在input data-field="nickname"
<div class="form-group">
<label class="control-label col-xs-12 col-sm-2">{:__('Qjzj_place_id')}:</label>
<div class="col-xs-12 col-sm-8">
<input id="c-qjzj_place_id" data-rule="required" data-field="code" data-source="qjzj/place/index" class="form-control selectpage" name="row[qjzj_place_id]" type="text" value="">
</div>
</div>
edit.html文件代码
application\admin\view\qjzj\house\edit.html(添加)
<div class="form-group">
<label class="control-label col-xs-12 col-sm-2">{:__('Qjzj_place_id')}:</label>
<div class="col-xs-12 col-sm-8">
<input id="c-qjzj_place_id" data-rule="required" data-source="qjzj/place/index" class="form-control selectpage" name="row[qjzj_place_id]" type="text" value="{$row.qjzj_place_id|htmlentities}">
</div>
</div>
列表页显示关联name
在模型文件中定义关联关系:
application\admin\model\qjzj\House.php
这里是关联place这张表的数据
public function place()
{
return $this->belongsTo('Place', 'qjzj_place_id', 'id', [], 'LEFT')->setEagerlyType(0);
}
application\admin\controller\qjzj\House.php
在控制器中修改index方法,添加with关联查询:
注意:with 里面和House.php中place()名称要一致
$list = $this->model
->with(['admin','place'])
->where($where)
->order($sort, $order)
->paginate($limit);
house.js文件代码
public\assets\js\backend\qjzj\house.js
只添加columns里面的那一条数据
注意:一般CRUD自动生成的代码在index 表格中显示的是ID号,如果我们想显示关联表中其他的字段而不是ID,我们可以设置{field: 'place.name', title: __('Qjzj_place_id'), operate: 'LIKE', table: table, class: 'autocontent', formatter: Table.api.formatter.content}, 这个place要和House.php 模型中的place()名称要对应。后面的name就是我们想显示的place表中的字段。
table.bootstrapTable({
url: $.fn.bootstrapTable.defaults.extend.index_url,
pk: 'id',
sortName: 'id',
fixedColumns: true,
fixedRightNumber: 1,
columns: [
[
{field: 'place.name', title: __('Qjzj_place_id'), operate: 'LIKE', table: table, class: 'autocontent', formatter: Table.api.formatter.content},
]
]
});