Search code examples
phpyiiyii-cactiverecord

Yii check if the record already exsists in database table


I've got 2 models (producten and voorraad), and one controller (producten). So i've build a form inside the producten CRUD (create/update). This is a custom form:

<div class="form-group">
    <span class='btn btn-default addOption'>Optie toevoegen</span>
</div>
<div class='opties'>    

</div>
<div class="form-group">
    Verkrijgbaar als backorder?
    <select name="backorder">
        <option value="1">Ja</option>
        <option value="0">Nee</option>
    </select>
</div>

This is very easy. If you press on the button addOption, it will add a few form inputs.

Now when the form is being saved (here the trouble begins), it will always add the data from the form to the database. But i don't want that. I want the data to be checked first, if it already exsists, if so, it has to be replaced and not added again.

Is there a yii function for that, or how do I do this?

ProductenController piece:

foreach($_POST as $key => $value){
    if(substr($key, 0,5) == 'maat_'){
        $index_expl = explode('_',$key);
        $index = $index_expl['1'];

        $aantal = $_POST['aantal_'.$index];

        $maten = explode(',',$value);
        foreach($maten as $maat_key => $maat){
            $kleuren = explode(',',$_POST['kleur_'.$index]);
                foreach($kleuren as $kleur_key => $kleur){
                    $voorraad = new Voorraad();
                    $voorraad->product_id = $model->id;
                    $voorraad->maat = $maat;
                    $voorraad->kleur = $kleur;
                    $voorraad->aantal = $aantal;
                    $voorraad->backorder = (int)$_POST['backorder'];
                    $voorraad->save();
                }
        }
    }
}

Solution

  • Replace the following :

    $voorraad = new Voorraad();
    

    with :

    $voorraad = Voorraad::model()->findByPk($model->id); // assuming id is primary key, you can also use `findByAttributes`
    if($voorraad == null) $voorraad = new Voorraad();
    

    $voorraad->save(); is also used for updating the record.