场景描述:如下,我要做一个下拉框
客户来源是数据字典中的数据,电话销售、朋友介绍、移动广告是数据字典明细中的数据,前后者关系是一对多;
或许你已经知道了,我只要拿到客户来源,就能根据一对多关系拿到其相关的所有的数据字典明细了
1.先拿到客户来源
<el-form-item label="客户来源" prop="customerSource">
<el-select v-model="addForm.customerSource" placeholder="请选择客户来源">
<el-option v-for="(item, index) in customerSourceDic"
:key="index"
:value="item.value"
:label="item.label"></el-option>
</el-select>
</el-form-item>
/* 后台查询客户来源数据字典返回给customerSourceDic */
getCusDic() {
/* 在这里可以将传入的id写死为1 */
/* 因为查的是数据字典 */
this.$http.get("/systemDictionary/getDic/1").then(res => {
for (let result of res.data) {
this.customerSourceDic.push({
/* requence就是数据字典明细中的数据字典序号,根据该序号就能找到数据字典明细值 */
/* 这里用value标签接收,因为在customer中保存的实际上是数据字典序列,
只有查的时候才替换成数据字典明细值 */
value: result.requence,
label: result.name
});
}
});
},
2.Mapper中
SystemDictionary和SystemDictionaryItem是一对多的关系
SystemDictionaryMapper.xml:
<!-- 配置一对多 -->
<!-- 既然是一对多,那么一中某个属性必然要和多中某个属性相匹配,这样一与多才能产生关系,这个属性就是sn -->
<resultMap id="getDic" type="cn.myllxy.crm.domain.SystemDictionary">
<result property="id" column="id"/>
<result property="sn" column="sn"/>
<result property="intro" column="intro"/>
<result property="state" column="state"/>
<collection property="details" javaType="ArrayList"
ofType="cn.myllxy.crm.domain.SystemDictionaryItem"
column="sn"
select="cn.myllxy.crm.mapper.SystemDictionaryItemMapper.selectSystemDictionaryItemByParentSn">
<id property="id" column="id" javaType="long" jdbcType="BIGINT"/>
<result property="name" column="name" javaType="string" jdbcType="VARCHAR"/>
<result property="requence" column="requence" javaType="long" jdbcType="BIGINT"/>
<result property="intro" column="intro" javaType="string" jdbcType="VARCHAR"/>
</collection>
</resultMap>
<!-- 通过sn来查询数据字典,再查出对应所有数据字典明细 -->
<select id="selectBySn" resultMap="getDic" parameterType="long">
SELECT sd.id,sd.name,sd.sn
FROM t_systemdictionary sd WHERE sn=#{sd.sn}
</select>
SystemDictionaryItemMapper.xml:
<resultMap id="SystemDictionaryItemResultMap" type="cn.myllxy.crm.domain.SystemDictionaryItem">
<id column="id" property="id"/>
<result column="name" property="name"/>
<result column="requence" property="requence"/>
<result column="intro" property="intro"/>
<association property="parent" column="parent_sn" javaType="SystemDictionary">
<id property="id" column="id"/>
<result property="sn" column="sn"/>
<result property="intro" column="intro"/>
<result property="state" column="state"/>
</association>
</resultMap>
<select id="selectSystemDictionaryItemByParentSn" parameterType="long"
resultMap="SystemDictionaryItemResultMap">
SELECT * FROM t_systemdictionaryitem WHERE parent_sn = #{sn}
</select>
3.Controller
/**
* 返回数据字典明细实体对象集合用于页面数据显示
*
* @param sn
* @return
*/
@RequestMapping(value = "/getDic/{sn}", method = RequestMethod.GET)
@ResponseBody
public List<SystemDictionaryItem> getDic(@PathVariable("sn") Long sn) {
SystemDictionary systemDictionary = systemDictionaryService.selectBySn(sn);
return systemDictionary.getDetails();
}