Support the ongoing development of Laravel.io →
posted 10 years ago
Database
Last updated 2 years ago.
0

Did you ever get anywhere with this? The only thing that I found was from the old forum:

http://forumsarchive.laravel.io/viewtopic.php?id=2643

Basically doing a raw statement like you said.

Last updated 2 years ago.
0

I worked with the same issue. You can put the following method on your Model.

public function insertUpdate(array $attributes)
{
    $this->fill($attributes);
    
    if ($this->usesTimestamps()) {
        $this->updateTimestamps();
    }

    $attributes = $this->getAttributes();

    $query = $this->newBaseQueryBuilder();
    $processor = $query->getProcessor();
    $grammar = $query->getGrammar();

    $table = $grammar->wrapTable($this->getTable());
    $keyName = $this->getKeyName();
    $columns = $grammar->columnize(array_keys($attributes));
    $insertValues = $grammar->parameterize($attributes);

    $updateValues = [];

    if ($this->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));

    $this->setAttribute($keyName, $id);

    return $this;
}
Last updated 8 years ago.
0

Sign in to participate in this thread!

Eventy

Your banner here too?

Moderators

We'd like to thank these amazing companies for supporting us

Your logo here?

Laravel.io

The Laravel portal for problem solving, knowledge sharing and community building.

© 2024 Laravel.io - All rights reserved.