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'
),
}