I have a model and ready-made data in a table. In this model, I added a new field and made a connection with another table.
And in order not to manually fill in these fields for each record, I want to create a migration that will automatically fill in this field for all records.
Relationship table has two fields: post_id and author_id
I’m creating a migration where I get all existing post_id and try to add value to author_id:
public function safeUp()
{
/**
* @var Posts[] $posts
*/
$posts = Posts::find()->all();
foreach ($posts as $post) {
$item = new PostAuthor();
$item->setAttribute('post_id', $post->id);
$item->setAttribute('author_id', 2);
$item->save();
}
}
Now everything is working, and all existing posts are given an author_id with a value of 2.
But I would like to refine it a little, author_id can have a value from 1 to 4, and I want different values ββββto be added to each post in the migration.
Let’s say the first post gets author_id: 1
The second post will get author_id: 1, author_id: 2
Third post author_id: 1, author_id: 2, author_id: 3
And the fourth post respectively author_id: 1, author_id: 2, author_id: 3, author_id: 4
But how can I do this, because now all my posts will receive the same values