Keep id and id_user equal on updateOrCreate

Asked

Viewed 124 times

1

Hi, using the Slim Framework for php, I’m trying to make a updateOrCreate:

$eventos = Eventos::updateOrCreate(
     ["id" => $id, "id_usuario" => $id_usuario], 
     ["nome" => $nome, "descricao" => $descricao]
);

The problem is that when you do the update he has to keep the id_usuario and the id, I thought I’d put the id_usuario in the first "[]" but it gives the following error:

SQLSTATE[23000]: Integrity Constraint Violation: 1062 Duplicate entry '91' for key 'PRIMARY' (SQL: Insert into eventos (id, id_usuario, nome) values (91, 1, Kashmir))

It gives Insert instead of update because, how can I fix it ?


Follow the Events table model:

<?php

    class Eventos extends BaseModel{

        protected $table = "eventos";

        const UPDATED_AT = 'atualizado_em';
        const CREATED_AT = 'criado_em';

        protected $dateFormat = 'U';
        protected $fillable = ["id", "nome", "descricao", "id_thumbnail", "local", "endereco", "place_id", "data_hora_inicio", "data_hora_fim", "responsavel", "telefone1", "telefone2", "email", "site", "nota", "status", "categoria", "facebook_page_url", "id_usuario", "preco"];

    }

?>
  • Are you using Eloquent? It has the layout of this table

  • If he is creating it is because there is no event with the same id and id_usuario that you’re going through. That id_usuario has already been registered with id different. Add (Before your code) \DB::listen(function($sql) {&#xA; var_dump($sql);&#xA; }); and check the query generated. So you will see the error.

  • @Virgilionovic I am using the Eloquent yes, I will update the question with the model of the table

  • Alan the id is auto_incremento? if it is she can’t be in $fillable

1 answer

1


The code executed updateOrCreate is:

public static function updateOrCreate(array $attributes, array $values = array())
{
    $instance = static::firstOrNew($attributes);
    $instance->fill($values)->save();
    return $instance;
}

public static function firstOrNew(array $attributes)
{
    if ( ! is_null($instance = static::where($attributes)->first()))
    {
        return $instance;
    }
    return new static($attributes);
}

then the right thing would be:

$eventos = Eventos::updateOrCreate(
    ["id" => $id], 
    ["nome" => $nome, "descricao" => $descricao, "id_usuario" => $id_usuario]
);

where the search is for its identification, including in its model has the wrong configuration, where the id don’t have to stay inside $fillable, because it is automatically generated by the bank, then:

class Eventos extends BaseModel
{

    protected $table = "eventos";

    const UPDATED_AT = 'atualizado_em';
    const CREATED_AT = 'criado_em';

    protected $dateFormat = 'U';
    protected $fillable = ["nome","descricao", "id_thumbnail", 
                           "local", "endereco", "place_id", 
                           "data_hora_inicio", "data_hora_fim", 
                           "responsavel", "telefone1", 
                           "telefone2", "email", "site", "nota", 
                           "status", "categoria", 
                           "facebook_page_url", "id_usuario","preco"];

}

I would particularly do so:

$evento = Eventos::find($id);
if (!$evento) 
{
    $evento = new Eventos();
    $evento->fill(["nome"=>$nome,"descricao"=>$descricao,"id_usuario"=>$id_usuario]);
}
else
{
    $evento->fill(["nome"=>$nome,"descricao"=>$descricao]);
}
$evento->save();

Can also be created a Scope in his model:

class Eventos extends BaseModel
{

    protected $table = "eventos";

    const UPDATED_AT = 'atualizado_em';
    const CREATED_AT = 'criado_em';

    protected $dateFormat = 'U';
    protected $fillable = ["nome","descricao", "id_thumbnail", 
                           "local", "endereco", "place_id", 
                           "data_hora_inicio", "data_hora_fim", 
                           "responsavel", "telefone1", 
                           "telefone2", "email", "site", "nota", 
                           "status", "categoria", 
                           "facebook_page_url", "id_usuario","preco"];

    public function scopeGeneration($query, $id, $values = array())
    {
        $m = $query->find($id);
        if (!m)
        {
           $m = new Eventos();                              
        }  
        else
        {
          unset($values['id_usuario']);
        }          
        $m ->fill($values);
        $m->save();
        return $m;
    }

}

How to use:

$values = ["nome"=>$nome,"descricao"=>$descricao,"id_usuario"=>$id_usuario];
$evento = Eventos::generation($id,$values);
  • i need the id_usuario to be created in the Insert but no update, no update I want to keep the id_usuario that is already in the bank, so I thought I’d do it the way it is in the question... ?

  • I’ll fix the id problem in $fillable, vlw!

  • Check out @Alanps I’ll edit and put the id_usuario in the second array! take the test

  • the problem of putting the id_usuario is q when der update will update the field in the database, I could do another query checking if there is in the database the record and if there is an if to take the id_usuario but I think q would be "ugly" do so, I thought the eloquent had a better way of doing this

  • @Alanps will update the id_usuario to the same number or not ?

  • no, it is just this, it will change the id_usuario and I do not want it, can not update the id_usuario, just create

  • Alanps will make another solution

  • ready @Alanps.

  • @Alanps did another example with Scope.

Show 4 more comments

Browser other questions tagged

You are not signed in. Login or sign up in order to post.