【发布时间】:2018-03-17 11:29:37
【问题描述】:
假设我有 3 个表:
用户 - 图片 - 产品。
看起来是这样的。我如何轻松识别该行是针对用户还是针对产品的。
我的第一个解决方案是在图像/封面表中命名一个 (ID) 并让它引用 2 个表并添加一个具有 字符串数据类型 的 'type' 列,然后只存储 'user'和/或'product' 字符串,以确定'id' 是user_id 还是product_id。
除了将 2 个表引用到一个外键的明显错误之外。我的想法还有其他问题吗?
也许我可以添加两个(ID)。即user_id 和product_id 并将两者都声明为NULL。我将能够确定该行属于哪个表。
如果 user_id 的值为 '1' 且 product_id 为 NULL,则该行属于用户。
用于插入用户封面/图像的示例控制器/型号代码 sn-p。
控制器:
$insert['user_id'] = $this->user_id;
$insert['product_id'] = NULL;
$insert['original'] = $image_name;
$insert['thumbnail'] = $this->upload->data('raw_name').'_thumb';
$image_id = $this->model->insert_cover($insert);
if($image_id > 0){//do something }
型号:
public function insert_cover($data){
$query = $this->db->insert('cover/image', $data);
if($query){ return $this->db->insert_id(); }else{ return 0; }
}
我有将图像上传到我的项目文件夹'/assets/uploaded_images/' 的默认要求,但我想将所有产品图像显示为 200x200 并将所有用户图像显示为 100x100 所以我使用codeigniter中的image_lib对上传的原始图片进行大小调整,调整后的图片自动命名为'_thumb'后缀。
然后我将原始文件和缩略图的文件名存储到我的数据库中,当在我的视图上显示它们时,我只需添加一个 url 字符串
$cover = 'http://localhost/project_name/assets/uploaded_images/'.$file_name
无论如何,我可以在这里应用什么方法来轻松识别该行属于哪个表?
我是否选择 2 具有 NULL 值的 id?我要添加一个字符串形式的“类型”列吗?
但为什么我觉得它俗气/松散?每当我插入一些我必须添加的东西时:
$insert['type'] = 'user';
我认为这是因为我无法控制“类型”列。
如果我添加另一个名为 image_type 或 cover_type 的两列表会怎样。即type_id和type_name。
然后,每当我插入图像表时,我都必须先查询'type' 列。
//inserting user image/cover
$type = $this->model->check_type('user');
if($type != NULL){
// do something
}
public function check_Type($type){
$this->db->select('type_id');
$query = $this->db->get_where('image_type', array('type_name' = $type));
if($query->num_rows() > 0){
foreach($query->result() as $row){
$type = $row->type_id;}
return $type;
}else{ return NULL; }
【问题讨论】:
标签: php mysql codeigniter