Yii2. Работа с несколькими базами данных
Простой пример работы с несколькими базами данных в Yii framework 2.
Добавляем настройки подключения к нескольким БД в Yii2
Для работы с несколькими базами данных в Yii2, нужно добавить все новые соединения в файл config/web.php:
Также можно использовать отдельный файл для подключения новой базы данных, это делается следующим образом:
Не переименовываете свойство «db» компонента, так как это приведет к ошибке.
Указываем нужную БД для использования в моделе Yii2
Для использования новой базы данных в модели, нужно переопределить конфигурацию «db» установленную по умолчанию, делаем это следующим образом:
Функция getDb устанавливает нужное нам соединения с БД для модели.
Работа joinWith() для разных баз данных в Yii2
И так, когда обе таблицы находятся в одной базе данных, например: Author (model \app\models\Author.php) и Post (model \app\models\Post.php) мы делаем так:
Такая связь для таблиц находящихся в разных база данных будет выглядеть так:
При этом таблица Post из базы данных myNewDB (модель: \app\models\Order.php), использует метод для настройки соединения с базой данных getDB().
И напоследок, используйте соединение с несколькими базами данных в одном приложении с умом, не надо делать разные базы для каждой таблицы, но в свою очередь и запихивать множество таблиц в одну базу (особенно при кардинальном отличии области применения) тоже не стоит.
Web разработчик, специализируюсь на разработке full stack веб-приложений.
Если у вас есть предложения или вопросы свяжитесь со мной: facebook
Соединение с базой данных в Yii 2.x
Часто требуется подключать базу в различных местах, поэтому распространенной практикой является настройка компонента приложения. Для этого в файле web.php прописываем следующий код:
Выносим подключение в файл db.php. В файле подключения вставляем следующий код:
Теперь вы можете получить доступ к подключению к текущей БД с помощью выражения Yii::$app->db , для доступа к последующей базе данных используйте выражение \Yii::$app->secondDb
Рассмотрим несколько примеров описания имени источника данных для разных СУБД
2 базы данных Yii2
Могу ли я одновременно работать с двумя базами данных в Yii2? Если да, то подскажите на примере пожалуйста.
![]()
Да. Вот короткий перевод ответа с английского StackOverflow, который поможет Вам. (оригинальные вопросы и ответ тут: https://stackoverflow.com/questions/27254540/yii-2-0-multiple-database-connection)
Для начала Вам необходимо создать по компоненту для каждого подключения:
Потом в коде своего приложения в моделях ActiveRecord Вам необходимо переопределить метод getDb() .
Модели, в которых Вы переопределили метод getDb() , указав db1 как соединение с базой, будут получать данные из базы db1, и наоборот:
Как подключить 2бд к сайту yii2 адвансед
The customary configuration of a Yii application includes just a single database section in the protected/config/main.php file, but it’s easy to extend this to support more than one, tying each Model to one of the databases.
We’ll extend the standard blog example to tie into a separate Advertising database: though it’s related to the blog, it’s still an independent system.
Config Setup ¶
The first step configures the second database into the configuration next to the first DB, and though you can call it db2 if you want, it it’s perhaps helpful to name it more usefully: we’re calling it dbadvert :
The parameters should generally follow the pattern of the first entry, but you must include the class parameter in the second so that Yii knows you’re defining a DB Connection object. It will fail without this.
Once this is defined, the second database is referred to as Yii::app()->dbadvert rather than Yii::app()->db (of course, the first is still available).
But we can do much better integration than this, starting with Gii and ending with AR support.
Using Gii ¶
Gii can use multiple database connections in Yii > 1.1.11.
If you are using a previous version, Gii only knows how to use the primary database connection, so for a brief time while creating models/controllers/crud, you’ll have to edit your protected/config/main.php file to temporarily make the advertising database the primary db connection:
Once this is done, use the Gii code generator to create what you need, then edit your config file back to make both database connections live.
GetDbConnection() override ¶
Every model defined in protected/models/*.php includes GetDbConnection() in the base class, and it returns a handle to the DB connection object for the primary database. We need to override this method in the models representing the advertising database to return the second DB connection.
Though it’s possible to do this in the model definition file itself, this doesn’t scale well as it would duplicate a lot of code if more than one model lives in the Advertising database. Better is to use a custom wrapper class to CActiveRecord where this can be centralized.
The notion of custom wrapper classes is described in this wiki article, and we’ll assume that you’ve created a protected/components/MyActiveRecord.php file, and taught all of your model files to extend MyActiveRecord rather than CActiveRecord .
This method is purposely static: the underlying cached $dbadvert value is, so the function may as well be be too. Now, with this helper prepared, we can edit the model itself:
Now this model will properly fetch from the Advertising database instead of the blog database, and this can be extended to as many models as you like.