Created
August 6, 2018 13:02
-
-
Save Artistan/ea9ed99c6ea04eb62384816391193616 to your computer and use it in GitHub Desktop.
Upsert Eloquent Model
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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); | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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