首页 > 其他 > 详细

TP中关联模型的使用

时间:2020-05-29 16:27:46      阅读:48      评论:0      收藏:0      [点我收藏+]
class BFinanceProduct extends Common
{
protected $pk = ‘finance_product_id‘;
/**
* 关联机构
*/
public function organs()
{
return $this->hasOne(‘BFinanceOrgan‘,‘organ_id‘,‘finance_organ_id‘);
}

/**
* @desc 属性、属性值
*/
public function attrValue(){
return $this->belongsToMany(‘BFinanceAttrValue‘,‘BFinanceProductTypeAttr‘,‘finance_attr_value_id‘,‘finance_product_id‘);
}

/**
* 金融类型
*/
public function type()
{
return $this->hasOne(‘BFinanceType‘, ‘finance_type_id‘, ‘finance_type_id‘);
}
/**
* @param $where
* @param string $field
* @desc 根据条件获取金融产品数据
* @date 2020/5/26
*/
public function getFinanceProductByCondition($where,$field=‘*‘,$order=‘sort desc‘){
$map=[];
$map[] = [‘is_del‘,‘=‘,0];
$data = $this->getList($map,$field,$order);
if(!$data->isEmpty()){
$data->load([‘type‘,‘organs‘,‘attrValue‘=>[‘attrName‘]]);
}
return $data;
}

/**
* @param $where
* @desc 获取金融产品详情、关联数
*/
public function getInfoByCondition($where){
$info = $this->with([‘organs‘,‘type‘,‘attrValue‘=>[‘attrName‘]])->where($where)->find();
if($info){
$this->formatdata($info);
return $info;
}else{
return null;
}
}

}

用金融产品的模型类作为例子:
$data = $this->getList($map,$field,$order);
查询列表的时候,每条数据对应的机构、分类都是一对一的关系所以用法如下
$data->load([‘organs‘,‘type‘]);

对应的属性和属性值是多对多的关系,所以写法如下

$data->load([‘attrValue‘=>[‘attrName‘]]);

其中 type、organs、attrValue 方法定义了他们之前的关系,以及关联条件,避免了平时我们取出数据对数据关系的处理。


其中注意isEmpty()的用法
1.{} 2.[]
只有第二种才能使用改方法判断。

By:jff

TP中关联模型的使用

原文:https://www.cnblogs.com/widgetbox/p/jiaofeifei.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!