insert-on-duplicate-key icon indicating copy to clipboard operation
insert-on-duplicate-key copied to clipboard

Use the connection that was set on the model instance

Open reno1979 opened this issue 8 years ago • 2 comments

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);
    }

reno1979 avatar Feb 15 '17 08:02 reno1979

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';
}

yadakhov avatar Nov 03 '17 14:11 yadakhov

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.

dsandber avatar Feb 07 '19 14:02 dsandber