verificar validar saber registros registro existe datos buscar php laravel

php - validar - Inserte un nuevo registro si no existe y actualice si existe, laravel elocuente



validar si un registro existe en la base de datos laravel (12)

¿Hay alguna forma abreviada de insertar un nuevo registro si no existe y actualizar el registro si existe? el siguiente es el código que estoy usando.

$shopOwner = ShopMeta::where(''shopId'', ''='', $theID)->where(''metadataKey'', ''='', 2001)->first(); if ($shopOwner==null){ insert new record into database } else { update the existing record }

Gracias


¿No es esto lo mismo que updateOrCreate ()?

Es similar pero no es lo mismo. UpdateOrCreate () solo funcionará para una fila a la vez que no permite la inserción masiva. InsertOnDuplicateKey funcionará en muchas filas.

https://github.com/yadakhov/insert-on-duplicate-key


Actualizado: 27 de agosto de 2014 - [ updateOrCreate Built into core ...]

Solo en caso de que las personas sigan encontrándose con esto ... descubrí unas semanas después de escribir esto, que esto es de hecho parte del núcleo de Eloquent de Laravel ...

Excavar en los métodos equivalentes de Eloquent. Puedes ver aquí:

https://github.com/laravel/framework/blob/4.2/src/Illuminate/Database/Eloquent/Model.php#L553

en: 570 y: 553

/** * Create or update a record matching the attributes, and fill it with values. * * @param array $attributes * @param array $values * @return static */ public static function updateOrCreate(array $attributes, array $values = array()) { $instance = static::firstOrNew($attributes); $instance->fill($values)->save(); return $instance; }

Vieja respuesta a continuación

Me pregunto si hay alguna funcionalidad L4 incorporada para hacer esto de alguna manera, como por ejemplo:

$row = DB::table(''table'')->where(''id'', ''='', $id)->first(); // Fancy field => data assignments here $row->save();

Creé este método hace unas semanas ...

// Within a Model extends Eloquent public static function createOrUpdate($formatted_array) { $row = Model::find($formatted_array[''id'']); if ($row === null) { Model::create($formatted_array); Session::flash(''footer_message'', "CREATED"); } else { $row->update($formatted_array); Session::flash(''footer_message'', "EXISITING"); } $affected_row = Model::find($formatted_array[''id'']); return $affected_row; }

Espero que eso ayude. Me encantaría ver una alternativa a esto si alguien tiene uno para compartir. @erikthedev_


Al igual que el método firstOrCreate, updateOrCreate persiste en el modelo, por lo que no es necesario llamar a save ()

// If there''s a flight from Oakland to San Diego, set the price to $99. // If no matching model exists, create one. $flight = App/Flight::updateOrCreate( [''departure'' => ''Oakland'', ''destination'' => ''San Diego''], [''price'' => 99] );

Y para tu problema

$shopOwner = ShopMeta::updateOrCreate( [''shopId'' => $theID, ''metadataKey'' => ''2001''], [''other field'' => ''val'' ,''other field'' => ''val'', ....] );



Como en Laravel> = 5.3 , si alguien todavía tiene curiosidad por saber cómo hacerlo de manera fácil. Es posible mediante: updateOrCreate() .

Por ejemplo, para una pregunta hecha, puedes usar algo como:

$matchThese = array(''shopId''=>$theID,''metadataKey''=>2001); ShopMeta::updateOrCreate($matchThese,[''shopOwner''=>''New One'']);

El código anterior verificará la tabla representada por ShopMeta, que probablemente sea shop_metas menos que no esté definido de otra manera en el modelo mismo

y tratará de encontrar la entrada con

columna shopId = $theID

y

columna metadateKey = 2001

y si encuentra, actualizará la columna shopOwner de la fila encontrada a New One .

Si encuentra más de una fila coincidente, actualizará la primera fila que signifique la que tenga la id primaria más baja.

Si no se encuentra, insertará una nueva fila con:

shopId = $theID , metadateKey = 2001 y shopOwner = New One

Aviso Verifique que su modelo tenga $fillable y asegúrese de que tenga el nombre de cada columna definida allí que desea insertar o actualizar y que las columnas de descanso tengan un valor predeterminado o que su columna de id aumente automáticamente.

De lo contrario arrojará un error al ejecutar el ejemplo anterior:

Illuminate/Database/QueryException with message ''SQLSTATE[HY000]: General error: 1364 Field ''...'' doesn''t have a default value (SQL: insert into `...` (`...`,.., `updated_at`, `created_at`) values (...,.., xxxx-xx-xx xx:xx:xx, xxxx-xx-xx xx:xx:xx))''

Como habría algún campo que necesitará valor al insertar una nueva fila y no será posible ya que no está definido en $fillable o no tiene valor predeterminado.

Para obtener más referencias, consulte la documentación de Laravel en: https://laravel.com/docs/5.3/eloquent

Un ejemplo de allí es:

// If there''s a flight from Oakland to San Diego, set the price to $99. // If no matching model exists, create one. $flight = App/Flight::updateOrCreate( [''departure'' => ''Oakland'', ''destination'' => ''San Diego''], [''price'' => 99] );

que prácticamente borra todo.

Espero que ayude


En realidad, firstOrCreate no se actualizaría en caso de que el registro ya exista en el DB. Mejoré un poco la solución de Erik ya que realmente necesitaba actualizar una tabla que tiene valores únicos no solo para la columna "id"

/** * If the register exists in the table, it updates it. * Otherwise it creates it * @param array $data Data to Insert/Update * @param array $keys Keys to check for in the table * @return Object */ static function createOrUpdate($data, $keys) { $record = self::where($keys)->first(); if (is_null($record)) { return self::create($data); } else { return self::where($keys)->update($data); } }

Entonces lo usarías así:

Model::createOrUpdate( array( ''id_a'' => 1, ''foo'' => ''bar'' ), array( ''id_a'' => 1 ) );


Función de guardar:

$shopOwner->save()

ya haz lo que quieras ...

Código de Laravel:

// If the model already exists in the database we can just update our record // that is already in this database using the current IDs in this "where" // clause to only update this model. Otherwise, we''ll just insert them. if ($this->exists) { $saved = $this->performUpdate($query); } // If the model is brand new, we''ll insert it into our database and set the // ID attribute on the model to the value of the newly inserted row''s ID // which is typically an auto-increment value managed by the database. else { $saved = $this->performInsert($query); }


Una opción más si su identificación no es autoincrement y usted sabe cuál insertar / actualizar:

$object = MyModel::findOrNew($id); //assign attributes to update... $object->save();


como @JuanchoRamone publicado anteriormente (gracias a @Juancho) es muy útil para mí, pero si tus datos son una matriz, deberías modificar algo como esto:

public static function createOrUpdate($data, $keys) { $record = self::where($keys)->first(); if (is_null($record)) { return self::create($data); } else { return $record->update($data); } }


verificar si un usuario existe o no. Si no inserte

$exist = DB::table(''User'')->where([''username''=>$username,''password''=>$password])->get(); if(count($exist) >0) { echo "User already exist";; } else { $data=array(''username''=>$username,''password''=>$password); DB::table(''User'')->insert($data); } Laravel 5.4


firstOrNew creará un registro si no existe para actualizar una fila si ya existe e ingrese si no existe, puede usar updateOrCreate her is the complete exmaple

// Si hay un vuelo de Oakland a San Diego, establezca el precio a $ 99.

// Si no existe un modelo coincidente, cree uno. $flight = App/Flight::updateOrCreate( [''departure'' => ''Oakland'', ''destination'' => ''San Diego''], [''price'' => 99] );

Documento de referencia aquí: ( https://laravel.com/docs/5.5/eloquent )


$shopOwner = ShopMeta::firstOrNew(array(''shopId'' => $theID,''metadataKey'' => 2001));

Luego haga sus cambios y ahorre. Tenga en cuenta que firstOrNew no hace la inserción si no se encuentra, si la necesita, entonces es la primera vez que crea.