Skip to content

Instantly share code, notes, and snippets.

@techouse
Created July 3, 2017 13:29
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save techouse/ef61fd73cca0e392b90f73e6ef8a9e9f to your computer and use it in GitHub Desktop.
Save techouse/ef61fd73cca0e392b90f73e6ef8a9e9f to your computer and use it in GitHub Desktop.
insertIgnore
<?php
namespace App;
trait InsertIgnore
{
/**
* @param array $attributes
*
* @return static
*/
public static function insertIgnore(array $attributes = [])
{
$model = new static($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));
$values = $grammar->parameterize($attributes);
$sql = "INSERT IGNORE INTO {$table} ({$columns}) VALUES ({$values})";
$id = $processor->processInsertGetId($query, $sql, array_values($attributes));
$model->setAttribute($keyName, $id);
return $model;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment