INSERT IGNORE using Laravel's Fluent

前端 未结 10 1317
执笔经年
执笔经年 2020-12-11 02:12

Is there a quick way to modify a SQL query generated by Laravel\'s Fluent to have an INSERT IGNORE instead of the usual INSERT?

I\'m trying

10条回答
  •  误落风尘
    2020-12-11 03:07

    I couldn't monkey patch as suggested in Rastislav's answer.

    This is what worked for me:

    1. Override compileInsert method in a custom Query Grammar class, which extends the framework's MySqlGrammar class.

    2. Use an instance of this custom grammar class by calling the setQueryGrammar method from the DB connection instance.

    So, the class code is like this:

    wrapTable($query->from);
    
            if (! is_array(reset($values))) {
                $values = [$values];
            }
    
            $columns = $this->columnize(array_keys(reset($values)));
    
            // We need to build a list of parameter place-holders of values that are bound
            // to the query. Each insert should have the exact same amount of parameter
            // bindings so we will loop through the record and parameterize them all.
            $parameters = collect($values)->map(function ($record) {
                return '('.$this->parameterize($record).')';
            })->implode(', ');
    
            return "insert ignore into $table ($columns) values $parameters";
        }
    }
    

    I copied the compileInsert method from the framework's class and then, inside the method, I have only changed insert to insert ignore. Everything else has been kept the same.

    Then, in the specific spot of code, in the application (a scheduled task), where I needed "insert ignore", I have simply done as follows:

    setQueryGrammar(new CustomMySqlGrammar());
    
            // et cetera... for example:
            ModelClass::insert($data);
        }
    }
    

提交回复
热议问题