標籤:io ar sp for on art bs as tt
這裡以商品與商品類別為例
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‘
),
}
thinkphp 關聯模型 注意點