КОНДИТЕР: проверьте, существует ли ингредиент

У меня есть ингредиент таблицы, состоящий из (ингредиент_ид, имя), категория, состоящая из (категория_ид, имя) и категория_средства, состоящая из (ингредиент_ид, категория_ид). Я создаю форму для добавления многих ингредиентов по категориям, и я хочу проверить, если 1 или более ингредиентов уже существуют, тогда мне нужно будет только получить идентификаторы ингредиента, а затем другие ингредиенты, которые не существуют, будут вставлены в мою базу данных , ребята, вы можете помочь мне, пожалуйста?

Вот мой код:
ПОСМОТРЕТЬ:

    <?php echo form_open('dashboard/uploadIngredients', 'class="form-horizontal" enctype="multipart/form-data"'); ?>
<div class="form-group">
<div class="col-sm-10">

<select required class="form-control" name="ingredient_category">

<option value="" selected disabled>Select Ingredient Category</option>
<option value="All">All</option>
<?php foreach($this->products_model->getCategory() as $row): ?>
<option value="<?php echo $row->category_id ?>"><?php echo $row->category_name; ?></option>
<?php endforeach; ?>
</select>

</div>
</div>
<div class="form-group">
<div class="col-sm-10">
<textarea class="form-control" name="ingredients" rows="5" placeholder="Ingredients (EX. onion, oil, pasta)" required></textarea>
</div>
</div>

<div class='form-group'>
<div class="col-sm-10">
<button class="btn btn-lg btn-positive" type="submit"><i class="glyphicon glyphicon-ok"></i> Save Ingredient</button>
</div>
</div>
<?php echo form_close(); ?>

ДИСПЕТЧЕР:

 public function uploadIngredients()
{

foreach(explode(',', $this->input->post('ingredients')) as $key => $value)
{
$saveData[] = array('ingredient_id' => null,
'name'  => trim($value)
);
}

$ingredient_id = $this->products_model->saveIngredients($saveData);
foreach (explode(',', $this->input->post('ingredient_category')) as $key => $value)
{
foreach ( $ingredient_id as $key => $str ){
$joinData[] = array(
'ingredient_id'     => $str,
'category_id'       => intval($value)
);
}
//var_dump($joinData); die();
$this->products_model->saveCategoryIngredients($joinData);

redirect('dashboard/add_ingredients');
}}

МОДЕЛЬ:

 public function saveIngredients($ingredient_id)
{
foreach($ingredient_id as $row => $value) {
$query=$this->db->where('ingredient_id', $value->ingredient_id);
$this->db->insert('ingredient', $value);
$insert_id[] = $this->db->insert_id();
}return $insert_id;
}public function saveCategoryIngredients($data)
{

foreach($data as $row => $value)
{
$this->db->insert('category_ingredient', $value);
$insert_id[] = $this->db->insert_id();
}
return $insert_id;}
}

0

Решение

Вам просто нужно добавить функцию к вашей модели, например так:

<?php

public function getIngredientByName($name) {
return $this->db
->from('ingredient I')
->where('I.name', $name)
->get()->row(); //Will return the row of ingredient if ingredient exists, else null
}

И в вашем контроллере:

<?php
foreach(explode(',', $this->input->post('ingredients')) as $key => $value)
{
if (!$this->products_model->getIngredientByName($value)) {
$saveData[] = array(
'ingredient_id' => null,
'name'  => trim($value)
);
}
}
0

Другие решения

Спасибо Gwendal за ответ на этот вопрос, я немного изменяю этот ответ, чтобы предотвратить повторяющиеся вставки, например: — если пользователь вставляет Карамельная тросточка но мы имеем в нашей базе данных Карамельная тросточка тогда с кодом ответа у нас будет 2 карамельная тросточка чтобы избежать такого типа вставок, мы можем использовать этот код для модели

<?php

public function getIngredientByName($name) {
return $this->db
->from('ingredient I')
-> where("( REPLACE( LOWER(I.name), ' ', '') LIKE '".strtolower(preg_replace('/\s+/', '', $name)) ."%')")
->get()->row(); //Will return the row of ingredient if ingredient exists, else null
}

для контроллера так же, как

<?php
foreach(explode(',', $this->input->post('ingredients')) as $key => $value)
{
if (!$this->products_model->getIngredientByName($value)) {
$saveData[] = array(
'ingredient_id' => null,
'name'  => trim($value)
);
}
}
0

По вопросам рекламы ammmcru@yandex.ru
Adblock
detector