@reech

Как создать запись в БД с помощью Eloquent?

Есть два connection в настройках: локальная БД и удаленная. Нужно создать запись в удаленной.

$model = new \App\Models\Setting();
$model->setConnection($request->dataset['connection']);
$model->create($request->all());


Указываю конкретный connection из настроек. В итоге запись создается в локальной. Проблема только с методом create(). Во всех остальных методах все данные в модель поступают из удаленной БД.

Перед методом $model->create специально сделал дамп модели:

65439a2b4f9b4a29bc8448024729b51a.png

Указан правильный connection, но модель добавляет запись, используя connection по-умолчанию. Как исправить эту ошибку?
  • Вопрос задан
  • 228 просмотров
Решения вопроса 2
miraage
@miraage
Старый прогер
Метод create - статический.
Source code.
Ответ написан
Комментировать
@reech Автор вопроса
Нашел ответ на stackoverflow.com/questions/29069101/multi-tenancy...

The problem is that setConnection() works on an instance of a class, but the create() method is a static method on the class itself. In your repository, $this->product is an instance of the Product class. Using setConnection() on this instance before doing queries will work fine, but you'll need to do a little more manual work if you want to use separate connections on the static methods (such as create()).

All the create() method does is instantiate a new instance with the given attributes and then call save(). So, instead of calling create() on the Product model, you'll just need to do this manually.

class ProductRepository {
    public function create(array $attributes, $connection = null) {
        $product = $this->product->newInstance($attributes);
        $product->setConnection($connection ?: $this->product->getConnectionName());
        $product->save();
        return $product;
    }
}

You could also override the static create() method on the Product model to accept a connection, as well.

class Product extends Model {
    public static function create(array $attributes, $connection = null) {
        $model = new static($attributes);
        $model->setConnection($connection ?: $this->connection);
        $model->save();
        return $model;
    }
}

class ProductRepository {
    public function create(array $attributes, $connection = null) {
        $connection = $connection ?: $this->product->getConnectionName()
        return $this->product->create($attributes, $connection);
    }
}
Ответ написан
Комментировать
Пригласить эксперта
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Войти через центр авторизации
Похожие вопросы