Skip to content

Instantly share code, notes, and snippets.

@techouse
Created July 3, 2017 13:29
Show Gist options
  • Save techouse/ef61fd73cca0e392b90f73e6ef8a9e9f to your computer and use it in GitHub Desktop.
Save techouse/ef61fd73cca0e392b90f73e6ef8a9e9f to your computer and use it in GitHub Desktop.

Revisions

  1. techouse created this gist Jul 3, 2017.
    39 changes: 39 additions & 0 deletions InsertIgnore.php
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,39 @@
    <?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;
    }
    }