thinkphp 关联模型 注意点

这里以商品与商品类别为例

1、表名为goods_type  则模型名为GoodsTypeModel,若模型名不是这,得另外定义   protected $tableName=模型对应主表名

2、模型类必须继承RelationModel

3、三种关联关系 

一对一关联 :ONE_TO_ONE,包括HAS_ONE和BELONGS_TO
一对多关联 :ONE_TO_MANY,包括HAS_MANY和BELONGS_TO
多对多关联 :MANY_TO_MANY ,这个要专门定义一个表来表示两个表间多对多关系

(1)一对一实例:商品与商品属性

商品模型类

class GoodsModel extends RelationModel{

protected $fields = array();

protected $_link = array(

'JhGoodsAttribute' => array(
  'mapping_type' => HAS_ONE,
  'class_name' => 'JhGoodsAttribute',
  'foreign_key' => 'goods_id',
),

);

}

商品属性模型类

class JhGoodsAttributeModel extends RelationModel {

protected $fields = array(
'goods_id', 'sale_price', 'showname', 'original_price', 'suggest_price', 'up_num', 'volume', 'issues_time', 'pagedetails', 'shelves', '_pk' => 'goods_id', '_autoinc' => false
);
protected $_link = array(
'Goods' => BELONGS_TO,
);

}

(2)一对多模型  员工与权限

员工模型类

class StaffModel extends RelationModel {

protected $fields = array(
'identity', 'name', 'num', 'pswd', 'department_id', 'job', '_pk' => 'num', '_autoinc' => false
);
protected $_link = array(
'Authority' => array(
  'mapping_type' => HAS_MANY,
  'class_name' => 'Authority',
  'mapping_name' => 'Authority',
  'mapping_key' => 'num',
  'foreign_key' => 'staff_num'
),

权限类

class AuthorityModel extends RelationModel {

protected $fields = array(
'id', 'staff_num', 'authority_num', '_pk' => 'id', '_autoinc' => true
);
protected $_link = array(
'Staff' => BELONGS_TO
);

}

(3)多对多关系  商品和商品类别

商品类 

class GoodsModel extends RelationModel {

protected $fields = array(
'id', 'name', 'code', 'details', 'specification', 'pack', 'weight', 'volume', 'unit', 'remark', 'expire_threshopld', 'min_threshopld', 'producer_id', '_pk' => 'id', '_autoinc' => true
);
protected $_link = array(
'GoodsType' => array(
  'mapping_type' => MANY_TO_MANY,
  'class_name' => 'GoodsType',
  'relation_foreign_key' => 'goods_type_id',
  'relation_table' => 'goods_type_relation'
),

}

 商品类别模型类

class GoodsTypeModel extends RelationModel {

protected $fields = array(
'id', 'parent_id', 'name', '_pk' => 'id', '_autoinc' => true
);
protected $_link = array(
'Goods' => array(
  'mapping_type' => MANY_TO_MANY,
  'class_name' => 'Goods',
  'relation_foreign_key' => 'goods_id',
  'foreign_key' => 'goods_type_id',
  'relation_table' => 'goods_type_relation'
),

}

 

转载于:https://www.cnblogs.com/pigmorn/p/4129108.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值