Skip to content

Instantly share code, notes, and snippets.

@Artistan Artistan/Upsert.php
Created Aug 6, 2018

Embed
What would you like to do?
Upsert Eloquent Model
<?php
namespace My\Database;
trait Upsert {
/**
* @requires @param string $primaryKey
* OR
* @requires @param array $unique_keys
*
* will try using $unique_keys first, otherwise primaryKey to determine how to find existing record
* will take the rest of the data as the updatable data and run updateOrCreate on the Eloquent Model
*/
/**
* a smarter updateOrCreate
*
* @param array $allData
* @param bool $unique
* @return \Illuminate\Database\Eloquent\Model
*/
public function upsert($allData,$unique=true)
{
if ($unique && ! empty($this->unique_keys)) {
$keys = is_array($this->unique_keys) ? $this->unique_keys : [$this->unique_keys];
} else {
$keys = is_array($this->primaryKey) ? $this->primaryKey : [$this->primaryKey];
}
$unique_search = array_intersect_key($allData,array_combine($keys,$keys));
$updatable = array_diff_key($allData,$unique_search);
return parent::updateOrCreate($unique_search,$updatable);
}
}
<?php
namespace My\Database;
use Illuminate\Database\Eloquent\Model;
/**
* Class ModelNumberOne
*
* @package My\Database
*
* @mixin \Illuminate\Database\Eloquent\Concerns\QueriesRelationships
* @mixin \Illuminate\Database\Concerns\BuildsQueries
* @mixin \Illuminate\Database\Eloquent\Builder
*/
class ModelNumberOne extends Model
{
use Upsert;
protected $unique_keys = [
'owner_id',
'reference_id',
];
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.