Certainly! To implement a newsletter feature using Yii2 with two separate tables in a database—one for storing subscribers and the other for the newsletters—you need to create two migrations. Below, you will find the code for creating these migrations.
Migration for newsletter_subscriber
The first migration is for creating the newsletter_subscriber table, which will store the details of each subscriber.
use yii\db\Migration;
/**
* Handles the creation of table `{{%newsletter_subscriber}}`.
*/
class m231029_000001_create_newsletter_subscriber_table extends Migration
{
/**
* {@inheritdoc}
*/
public function safeUp()
{
$this->createTable('{{%newsletter_subscriber}}', [
'id' => $this->primaryKey(),
'email' => $this->string()->notNull()->unique(),
'name' => $this->string(),
'status' => $this->smallInteger()->notNull()->defaultValue(1), // 1-active, 0-inactive
'created_at' => $this->integer()->notNull(),
'updated_at' => $this->integer()->notNull(),
]);
}
/**
* {@inheritdoc}
*/
public function safeDown()
{
$this->dropTable('{{%newsletter_subscriber}}');
}
}
Migration for newsletter
The second migration is for creating the newsletter table, which will store each newsletter content.
use yii\db\Migration;
/**
* Handles the creation of table `{{%newsletter}}`.
*/
class m231029_000002_create_newsletter_table extends Migration
{
/**
* {@inheritdoc}
*/
public function safeUp()
{
$this->createTable('{{%newsletter}}', [
'id' => $this->primaryKey(),
'title' => $this->string()->notNull(),
'content' => $this->text()->notNull(),
'status' => $this->smallInteger()->notNull()->defaultValue(1), // 1-active, 0-inactive
'created_at' => $this->integer()->notNull(),
'updated_at' => $this->integer()->notNull(),
]);
}
/**
* {@inheritdoc}
*/
public function safeDown()
{
$this->dropTable('{{%newsletter}}');
}
}
Explanation
Running the Migrations
Make sure both migration files are located in your console/migrations directory (or wherever you keep your migrations in Yii2). Run the following command to apply these migrations:
php yii migrate
This setup will provide you with the basic schema to manage subscribers and newsletters on your website. Adjust fields and data types as needed according to your specific requirements.