laravel 批量插入并在遇到重复键时更新

/**
 * 批量插入并在遇到重复键时更新
 * @param array $values
 * @return bool
 */
public static function insertOnDuplicate(array $values)
{
    if (empty($values)) {
        return true;
    }

    if (!is_array(reset($values))) {
        $values = [$values];
    }

    foreach ($values as $key => $value) {
        ksort($value);
        $values[$key] = $value;
    }

    $eloquentQuery = static::query();
    $sql = static::compileInsertOnDuplicate($eloquentQuery, $values);
    return $eloquentQuery->getConnection()->statement($sql, Arr::flatten($values, 1));
}

/**
 * @param Builder $query
 * @param array $values
 * @return string
 */
protected static function compileInsertOnDuplicate(Builder $query, array $values)
{
    $baseQueryBuilder = $query->getQuery();

    $table = $baseQueryBuilder->getGrammar()->wrapTable($baseQueryBuilder->from);

    if (!is_array(reset($values))) {
        $values = [$values];
    }

    $columns = $baseQueryBuilder->getGrammar()->columnize(array_keys(reset($values)));

    $parameters = collect($values)->map(function ($record) use ($baseQueryBuilder) {
        return '('.$baseQueryBuilder->getGrammar()->parameterize($record).')';
    })->implode(', ');

    $duplicates = collect(explode(',', $columns))->map(function ($column) {
        return "$column = values($column)";
    })->implode(', ');

    return "insert into $table ($columns) values $parameters on duplicate key update $duplicates";
}
posted @ 2024-08-15 14:09  pine007  阅读(38)  评论(0编辑  收藏  举报