mysql createorupdate,Laravel 5.1 Create or Update on Duplicate

Add the follow method insertUpdate to your Model <?php namespace App; use Illuminate\Auth\Authenticatable; use Illuminate\Database\Eloquent\Model; use Illuminate\Auth\Passwords\CanResetPassword; use Illuminate\Foundation\Auth\Access\Authorizable; use Illuminate\Contracts\Auth\Authenticatable as AuthenticatableContract; use Illuminate\Contracts\Auth\Access\Authorizable as AuthorizableContract; use Illuminate\Contracts\Auth\CanResetPassword as CanResetPasswordContract; class User extends Model implements AuthenticatableContract, AuthorizableContract, CanResetPasswordContract { use Authenticatable, Authorizable, CanResetPassword; /** * The database table used by the model. * * @var string */ protected $table = 'users'; /** * The attributes that are mass assignable. * * @var array */ protected $fillable = ['name', 'email', 'password']; /** * The attributes excluded from the model's JSON form. * * @var array */ protected $hidden = ['password', 'remember_token']; public static function insertUpdate(array $attributes = []) { $model = new static($attributes); $model->fill($attributes); if ($model->usesTimestamps()) { $model->updateTimestamps(); } $attributes = $model->getAttributes(); $query = $model->newBaseQueryBuilder(); $processor = $query->getProcessor(); $grammar = $query->getGrammar(); $table = $grammar->wrapTable($model->getTable()); $keyName = $model->getKeyName(); $columns = $grammar->columnize(array_keys($attributes)); $insertValues = $grammar->parameterize($attributes); $updateValues = []; if ($model->primaryKey !== null) { $updateValues[] = "{$grammar->wrap($keyName)} = LAST_INSERT_ID({$keyName})"; } foreach ($attributes as $k => $v) { $updateValues[] = sprintf("%s = '%s'", $grammar->wrap($k), $v); } $updateValues = join(',', $updateValues); $sql = "insert into {$table} ({$columns}) values ({$insertValues}) on duplicate key update {$updateValues}"; $id = $processor->processInsertGetId($query, $sql, array_values($attributes)); $model->setAttribute($keyName, $id); return $model; } }

You can use: App\User::insertUpdate([ 'name' => 'Marco Pedraza', 'email' => 'mpdrza@gmail.com' ]);

The next query it will be executed: insert into `users` (`name`, `email`, `updated_at`, `created_at`) values (?, ?, ?, ?) on duplicate key update `id` = LAST_INSERT_ID(id),`name` = 'Marco Pedraza',`email` = 'mpdrza@gmail.com',`updated_at` = '2016-11-02 01:30:05',`created_at` = '2016-11-02 01:30:05'

The method automatically add/remove the Eloquent timestamps if you have enabled or disabled.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值