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.
$posts = Posts::find()->all();
foreach ($posts as $index => $post) {
for($i = 0; $i < $index; $i++ ) {
$item = new PostAuthor();
$item->setAttribute('post_id', $posts->id);
$item->setAttribute('author_id', $i+1);
$item->save();
}
}
Now everything works so that the maximum number of author_id will be equal to the number of posts, i.e. for the first post it will be author_id: 1, for the second author_id: 1 and author_id: 2, and so on up to 6 author_id.
Can I limit the $index so that the maximum number here is 4, and when the author_id gets to 4, the loop starts over from 1?
$posts = Posts::find()->all();
foreach ($posts as $index => $post) {
for($i = 0; $j=0; $i < $index; $i++ ) {
if ( $j > 4 ) {
$j = 0;
}
$item = new PostAuthor();
$item->setAttribute('post_id', $posts->id);
$item->setAttribute('author_id', $j+1);
$item->save();
}
}