Model database configuration and application of yii2 (master-slave database configuration)

1. Multiple database configuration

  'db' => require(__DIR__ . '/db.php'),
  'gdb' => require(__DIR__ . '/gdb.php'),

The configuration file of db or gdb is as follows:

if (YII_ENV == 'dev') {
    return [
        'class' => 'yii\db\Connection',
        'dsn' => 'mysql:host=192.168.1.42;dbname=gather',
        'username' => 'lizhi',
        'password' => '123456',
        'charset' => 'utf8',
    ];
} else {
    return [
        'class' => 'yii\db\Connection',
        'dsn' => 'mysql:host=localhost;dbname=gather',
        'username' => 'gather',
        'password' => 'gather(!2',
        'charset' => 'utf8',
    ];
}

2. Call the corresponding database

/**
     * @return \yii\db\Connection the database connection used by this AR class.
     */
    public static function getDb()
    {
        return Yii::$app->get('gdb');
    }

Of course, you can also use gii to create it. Select the connection pool and the corresponding db name of your multi-database configuration will appear. such as gdb, db

3. Master-slave configuration

return [
    'class' => 'yii\db\Connection',
    // 配置从服务器
    'slaveConfig' => [
        'username' => 'root',
        'password' => '',
        'charset' => 'utf8',
        'tablePrefix' => '',
        'attributes' => [
            PDO::ATTR_TIMEOUT => 10,
        ],
    ],
    // 配置从服务器组
    'slaves' => [
        ['dsn' => 'mysql:host=localhost;dbname=chunyun']
    ],
    // 配置主服务器
    'masterConfig' => [
        'username' => 'root',
        'password' => '',
        'charset' => 'utf8',
        'attributes' => [// use a smaller connection timeout
            PDO::ATTR_TIMEOUT => 10,
        ],
    ],
    // 配置主服务器组
    'masters' => [
        ['dsn' => 'mysql:host=localhost;dbname=gather'],
    ]
];

The above is the application of yii2 to database configuration.

4. The application of model methods
Of course, yii2 also has some CDB class usages. I don't recommend createCommend to write sql. The model itself will bind a lot of functions for everyone to use and understand.
Next, we introduce some model methods.
(1) BeforeValidate method
The validate validation method is generally executed before the save operation. As the name implies: the operation done before validate, remember that it must return true after the operation.
You can assign some fields to default values ​​in this operation, so that you don't need to assign values ​​every time you add them.
Because the validate method has the following validation

 if (!$this->beforeValidate()) {
    return false;
}

Correspondingly, there is the afterValidate method, which I feel a little tasteless.

(2) beforeSave method
This generally belongs to the method after validate and before save, which is generally used for conditions, such as what data operation must be successful before save.

In order to do another save operation. Of course, there are many scenarios, it is up to you to use it. afterSave will not explain.

(3) Suggestions on query.
As for the data query of the model, I will not introduce it. There are definitely a lot of tutorials in this regard. There are still many friends who will tangle about the connection table,

The yii2 model supports joint tables, but from the perspective of performance, try to avoid joint tables.

How to avoid joint tables:

For example, if you query the article list, one of which is the category name, get the list of article categories through list, and put the category name in the corresponding category list,

Such an operation is more efficient than a joint table.

If the non-join table is not possible, you can write sql, which is convenient for future maintenance. The constructed sql has some shortcomings and shortcomings, and you can weigh the trade-offs yourself.

 
 
G
M
T
 
 
Detect languageAfrikaansAlbanianArabicArmenianAzerbaijaniBasqueBelarusianBengaliBosnianBulgarianCatalanCebuanoChichewaChinese (Simplified)Chinese (Traditional)CroatianCzechDanishDutchEnglishEsperantoEstonianFilipinoFinnishFrenchGalicianGeorgianGermanGreekGujaratiHaitian CreoleHausaHebrewHindiHmongHungarianIcelandicIgboIndonesianIrishItalianJapaneseJavaneseKannadaKazakhKhmerKoreanLaoLatinLatvianLithuanianMacedonianMalagasyMalayMalayalamMalteseMaoriMarathiMongolianMyanmar (Burmese)NepaliNorwegianPersianPolishPortuguesePunjabiRomanianRussianSerbianSesothoSinhalaSlovakSlovenianSomaliSpanishSundaneseSwahiliSwedishTajikTamilTeluguThaiTurkishUkrainianUrduUzbekVietnameseWelshYiddishYorubaZulu
 
AfrikaansAlbanianArabicArmenianAzerbaijaniBasqueBelarusianBengaliBosnianBulgarianCatalanCebuanoChichewaChinese (Simplified)Chinese (Traditional)CroatianCzechDanishDutchEnglishEsperantoEstonianFilipinoFinnishFrenchGalicianGeorgianGermanGreekGujaratiHaitian CreoleHausaHebrewHindiHmongHungarianIcelandicIgboIndonesianIrishItalianJapaneseJavaneseKannadaKazakhKhmerKoreanLaoLatinLatvianLithuanianMacedonianMalagasyMalayMalayalamMalteseMaoriMarathiMongolianMyanmar (Burmese)NepaliNorwegianPersianPolishPortuguesePunjabiRomanianRussianSerbianSesothoSinhalaSlovakSlovenianSomaliSpanishSundaneseSwahiliSwedishTajikTamilTeluguThaiTurkishUkrainianUrduUzbekVietnameseWelshYiddishYorubaZulu
 
 
 
 
 
 
 
 
 
Text-to-speech function is limited to 200 characters
 
 
Options : History : Feedback : Donate Close

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325161281&siteId=291194637