如何在数据库 CodeIgniter 中检查数组,如果它们不存在则添加它们
How to check for Array in Database CodeIgniter and if they don't exist Add them
所以我只想在键入的数据不存在时插入数据 and/or 如果用户决定删除它们,请删除它们;问题是它检查更多 > 1 值。
这应该是我关于同一主题、关系的总共三个问题中的最后一个(请参阅我关于个人资料的最后两个问题)。
所以我有三个 tables,如下所示:
AI = 自动递增。
ci_users: user_id(AI), 用户名, slug, 电子邮件, 传记。
ci_terms: term_id(AI), title, slug, body.
ci_relationship: id(AI), term_id, user_id, 类型.
我实际上正在尝试在编辑视图中执行此操作,在该视图中我从 ci_terms 获取所有条款,并且已经(直接添加到数据库中)ci_terms 附加到用户以下控制器:
public function edit($id){
// Verify user ID before updating/editing info
if($this->session->userdata('user_id') != $id) {
// Redirect to dashboard
redirect('users/dashboard');
}
// Field Rules
$this->form_validation->set_rules('email', 'Email', 'trim|required|min_length[7]|valid_email');
if ($this->form_validation->run() == FALSE) {
// Get user
$data['item'] = $this->User_model->get($id);
// Meta
$data['title'] = $this->settings->title.' | Edit '. ucfirst($data['item']->username);
// Get attached skills
$skills = array();
$skills[0] = 'Select Skills';
$skills_attached = $this->User_model->the_skills($id);
foreach($skills_attached as $skill){
$skills[$skill->term_id] = $skill->term_id;
}
$data['skills'] = $skills;
// Select Skills
$skill_options = array();
$skill_options[0] = 'Select Skills';
$skill_list = $this->Terms_model->get_list();
foreach($skill_list as $cat){
$skill_options[$cat->term_id] = $cat->title;
}
$data['skill_options'] = $skill_options;
//Load View Into Template
$this->template->load('public', 'default', 'users/edit', $data);
} else {
// Create User Data Array
$data = array(
'email' => strip_tags($this->input->post('email')),
'biography' => strip_tags($this->input->post('biography')),
);
// Update User
$this->User_model->update($id, $data);
// BEGINNING OF HERE IS WHERE I NEED HELP
// Here I try to check the selected ci_terms(term_id) in the database
$existent_skill = $this->User_model->existent_skill($this->input->post('term_id'));
// If the selected ci_terms(term_id) already exists, display an error
if (!empty($existent_skill)) {
// Create Message
$this->session->set_flashdata('error', 'You already have that one or more of those selected skills');
// Redirect to pages
redirect('users/edit/'.$id.'/'.$id->username);
} else {
// Display the data from ci_terms table
$skills = $this->Terms_model->get_list();
// Expect data to be array
$data = array();
foreach ($skills as $skill){
$data[] = array(
// The main problem how do I add the correct IDs to the array?
'term_id' => $skill->id,
'user_id' => $this->session->userdata('user_id'),
'type' => 'skill',
);
}
// If terms selected, add them
$this->db->insert_batch('ci_relationship', $data);
// I'm also trying to figure out a way to remove the terms that are already attached to the user if he/she decides not to want those skill anymore, any suggestion will be taken into practice.
// else if terms unselected, remove them
$this->User_model->delete_skills($id, $terms_id, $data);
// END OF HERE IS WHERE I NEED HELP
}
// Create Message
$this->session->set_flashdata('success', "You're account has been updated");
// Redirect to profile
redirect('users/dashboard');
}
}
以下是我如何将 ci_terms table 中附加的(对用户的)条款显示到视图中:
public function the_skills($id){
$this->db->select('*');
$this->db->from($this->relationship);
$this->db->where('user_id', $id);
$this->db->where('type', 'skill');
$query = $this->db->get();
if($query->num_rows() >= 1){
return $query->result();
} else {
return false;
}
}
这是我仍在尝试创建的方法,它会在添加之前检查所有选定的术语(如果它们不存在):
// Verify if relationship already exists
public function existent_skill($term_id) {
$query = $this->db->get_where($this->relationship, array(
'user_id' => $this->session->userdata('user_id'),
'term_id' => $term_id,
'type' => 'skill',
));
return $query->row_array();
}
继续,这里是假设(未测试)删除它们的函数,如果它们未从输入中选择:
// Delete un-selected skills
public function delete_skills($id, $terms_id, $data){
$this->db->from($this->relationship);
$this->db->where('user_id', $id);
$this->db->where_in('term_id', $terms_id);
$this->db->where('type', 'skill');
$this->db->delete($this->relationship, $data);
}
最后是我在其中使用带 select2 的下拉列表的视图:
<!-- Skills -->
<div class="form-group">
<?php echo form_label('Skills', 'skills'); ?>
<div class="input-group date"><div class="input-group-addon"><i class="fa fa-star" aria-hidden="true"></i></div>
<?php
$data = array(
'id' => 'term_id[]',
'name' => 'term_id[]',
);
$class = array(
'class' => 'form-control js-example-basic-multiple',
'multiple' => TRUE,
);
?>
<!-- $data is to provide the dropdown with the id and name -->
<!-- $skill_options is to get the terms from ci_terms in case the user wants to add them as their skill -->
<!-- $skills is to get the current term_id attached to the user which were added in the db -->
<!-- $class is to give the class of js-example-basic-multiple to enable select2 -->
<?= form_dropdown($data, $skill_options, $skills, $class); ?>
<script type="text/javascript">
// Select2 Input
$(document).ready(function () {
$('.js-example-basic-multiple').select2({
tags: true,
tokenSeparators: [',', ' '],
allowClear: true,
selectOnClose: false,
selectOnBlur: false,
});
});
</script>
</div>
</div>
以下仅为图片
所以我想要实现的是:
如您所见,HTML5(term_id, 1) 和 CSS(term_id, 2) 是附加的 term_id 和如果我取消选择它们,则应在单击更新按钮后将它们从 ci_relationship 中删除,并且在选择未附加的新术语时会发生相同(不是真的),应添加它们。
与 WordPress 使用的关系系统非常相似。
提前致谢。
我猜你想太多了——你应该只删除与该用户相关的所有项目,然后插入选定的新项目...
您的模型函数的示例可以是
public function updateSkills(array $arrSkills)
{
//in case if the array is empty you can stop the process here
if (empty($arrSkills)) return false;
//kill all associated items
$this->db
->where('user_id', $this->session->userdata('user_id'))
->where('type', 'skill');
->delete('ci_relationship');
//insert all items
$arrInsertData = [];
foreach($arrSkills AS $strSkill)
{
$arrInsertData[] = [
'term_id' => $strSkill,
'user_id' => $this->session->userdata('user_id'),
'type' => 'skill'
]
}
$this->db->insert_batch('ci_relationship', $arrInsertData);
return true;
}
你控制器中的部分可能看起来像
$data = array(
'email' => strip_tags($this->input->post('email')),
'biography' => strip_tags($this->input->post('biography')),
);
// Update User
$this->User_model->update($id, $data);
// BEGINNING OF HERE IS WHERE I NEED HELP
$blnSuccess = $this->User_model->updateSkills($this->input->post('term_id[]'));
当然你也可以加一条规则,如果需要term_id
$this->form_validation->set_rules('term_id[]', 'Term', 'trim|required');
所以我只想在键入的数据不存在时插入数据 and/or 如果用户决定删除它们,请删除它们;问题是它检查更多 > 1 值。
这应该是我关于同一主题、关系的总共三个问题中的最后一个(请参阅我关于个人资料的最后两个问题)。
所以我有三个 tables,如下所示:
AI = 自动递增。
ci_users: user_id(AI), 用户名, slug, 电子邮件, 传记。
ci_terms: term_id(AI), title, slug, body.
ci_relationship: id(AI), term_id, user_id, 类型.
我实际上正在尝试在编辑视图中执行此操作,在该视图中我从 ci_terms 获取所有条款,并且已经(直接添加到数据库中)ci_terms 附加到用户以下控制器:
public function edit($id){
// Verify user ID before updating/editing info
if($this->session->userdata('user_id') != $id) {
// Redirect to dashboard
redirect('users/dashboard');
}
// Field Rules
$this->form_validation->set_rules('email', 'Email', 'trim|required|min_length[7]|valid_email');
if ($this->form_validation->run() == FALSE) {
// Get user
$data['item'] = $this->User_model->get($id);
// Meta
$data['title'] = $this->settings->title.' | Edit '. ucfirst($data['item']->username);
// Get attached skills
$skills = array();
$skills[0] = 'Select Skills';
$skills_attached = $this->User_model->the_skills($id);
foreach($skills_attached as $skill){
$skills[$skill->term_id] = $skill->term_id;
}
$data['skills'] = $skills;
// Select Skills
$skill_options = array();
$skill_options[0] = 'Select Skills';
$skill_list = $this->Terms_model->get_list();
foreach($skill_list as $cat){
$skill_options[$cat->term_id] = $cat->title;
}
$data['skill_options'] = $skill_options;
//Load View Into Template
$this->template->load('public', 'default', 'users/edit', $data);
} else {
// Create User Data Array
$data = array(
'email' => strip_tags($this->input->post('email')),
'biography' => strip_tags($this->input->post('biography')),
);
// Update User
$this->User_model->update($id, $data);
// BEGINNING OF HERE IS WHERE I NEED HELP
// Here I try to check the selected ci_terms(term_id) in the database
$existent_skill = $this->User_model->existent_skill($this->input->post('term_id'));
// If the selected ci_terms(term_id) already exists, display an error
if (!empty($existent_skill)) {
// Create Message
$this->session->set_flashdata('error', 'You already have that one or more of those selected skills');
// Redirect to pages
redirect('users/edit/'.$id.'/'.$id->username);
} else {
// Display the data from ci_terms table
$skills = $this->Terms_model->get_list();
// Expect data to be array
$data = array();
foreach ($skills as $skill){
$data[] = array(
// The main problem how do I add the correct IDs to the array?
'term_id' => $skill->id,
'user_id' => $this->session->userdata('user_id'),
'type' => 'skill',
);
}
// If terms selected, add them
$this->db->insert_batch('ci_relationship', $data);
// I'm also trying to figure out a way to remove the terms that are already attached to the user if he/she decides not to want those skill anymore, any suggestion will be taken into practice.
// else if terms unselected, remove them
$this->User_model->delete_skills($id, $terms_id, $data);
// END OF HERE IS WHERE I NEED HELP
}
// Create Message
$this->session->set_flashdata('success', "You're account has been updated");
// Redirect to profile
redirect('users/dashboard');
}
}
以下是我如何将 ci_terms table 中附加的(对用户的)条款显示到视图中:
public function the_skills($id){
$this->db->select('*');
$this->db->from($this->relationship);
$this->db->where('user_id', $id);
$this->db->where('type', 'skill');
$query = $this->db->get();
if($query->num_rows() >= 1){
return $query->result();
} else {
return false;
}
}
这是我仍在尝试创建的方法,它会在添加之前检查所有选定的术语(如果它们不存在):
// Verify if relationship already exists
public function existent_skill($term_id) {
$query = $this->db->get_where($this->relationship, array(
'user_id' => $this->session->userdata('user_id'),
'term_id' => $term_id,
'type' => 'skill',
));
return $query->row_array();
}
继续,这里是假设(未测试)删除它们的函数,如果它们未从输入中选择:
// Delete un-selected skills
public function delete_skills($id, $terms_id, $data){
$this->db->from($this->relationship);
$this->db->where('user_id', $id);
$this->db->where_in('term_id', $terms_id);
$this->db->where('type', 'skill');
$this->db->delete($this->relationship, $data);
}
最后是我在其中使用带 select2 的下拉列表的视图:
<!-- Skills -->
<div class="form-group">
<?php echo form_label('Skills', 'skills'); ?>
<div class="input-group date"><div class="input-group-addon"><i class="fa fa-star" aria-hidden="true"></i></div>
<?php
$data = array(
'id' => 'term_id[]',
'name' => 'term_id[]',
);
$class = array(
'class' => 'form-control js-example-basic-multiple',
'multiple' => TRUE,
);
?>
<!-- $data is to provide the dropdown with the id and name -->
<!-- $skill_options is to get the terms from ci_terms in case the user wants to add them as their skill -->
<!-- $skills is to get the current term_id attached to the user which were added in the db -->
<!-- $class is to give the class of js-example-basic-multiple to enable select2 -->
<?= form_dropdown($data, $skill_options, $skills, $class); ?>
<script type="text/javascript">
// Select2 Input
$(document).ready(function () {
$('.js-example-basic-multiple').select2({
tags: true,
tokenSeparators: [',', ' '],
allowClear: true,
selectOnClose: false,
selectOnBlur: false,
});
});
</script>
</div>
</div>
以下仅为图片
所以我想要实现的是:
如您所见,HTML5(term_id, 1) 和 CSS(term_id, 2) 是附加的 term_id 和如果我取消选择它们,则应在单击更新按钮后将它们从 ci_relationship 中删除,并且在选择未附加的新术语时会发生相同(不是真的),应添加它们。
与 WordPress 使用的关系系统非常相似。
提前致谢。
我猜你想太多了——你应该只删除与该用户相关的所有项目,然后插入选定的新项目...
您的模型函数的示例可以是
public function updateSkills(array $arrSkills)
{
//in case if the array is empty you can stop the process here
if (empty($arrSkills)) return false;
//kill all associated items
$this->db
->where('user_id', $this->session->userdata('user_id'))
->where('type', 'skill');
->delete('ci_relationship');
//insert all items
$arrInsertData = [];
foreach($arrSkills AS $strSkill)
{
$arrInsertData[] = [
'term_id' => $strSkill,
'user_id' => $this->session->userdata('user_id'),
'type' => 'skill'
]
}
$this->db->insert_batch('ci_relationship', $arrInsertData);
return true;
}
你控制器中的部分可能看起来像
$data = array(
'email' => strip_tags($this->input->post('email')),
'biography' => strip_tags($this->input->post('biography')),
);
// Update User
$this->User_model->update($id, $data);
// BEGINNING OF HERE IS WHERE I NEED HELP
$blnSuccess = $this->User_model->updateSkills($this->input->post('term_id[]'));
当然你也可以加一条规则,如果需要term_id
$this->form_validation->set_rules('term_id[]', 'Term', 'trim|required');