insert-on-duplicate-key
insert-on-duplicate-key copied to clipboard
Use the connection that was set on the model instance
Copied from: https://github.com/yadakhov/insert-on-duplicate-key/pull/7
@yadakhov Thank you for creating this plugin.
Too bad the non default connection is not read from the instance of the model.
\App\Model::on('otherconnection')->getModel()->insertOnDuplicateKey([[....]]); // will still use the default connection
when rewriting the function to a non static, the instance settings are available.
public function insertOnDuplicateKey(array $data, array $updateColumns = null)
{
if (empty($data)) {
return false;
}
// Case where $data is not an array of arrays.
if (!isset($data[0])) {
$data = [$data];
}
$sql = self::buildInsertOnDuplicateSql($data, $updateColumns);
$data = self::inLineArray($data);
return $this->getConnection()->affectingStatement($sql, $data);
}
Hey,
I looked into fixing this issue a few months ago. It wasn't as easy as I thought due to the design of the current code using public static functions.
Have you tried setting the connections in the model file? Just create a new Model for the second connection.
class YouModel extends Model
{
protected $connection= 'second_db_connection';
}
I'm having the same issue -- I can't create a new model because the table name is determined dynamically at runtime. (I'm bulk inserting into a temporary table).
The issues seems to be here:
public static function getTableName()
{
$class = get_called_class();
return (new $class())->getTable();
}
Instead we want to call on the instance.