Search code examples
phpyii2

limit the number of entries and restart after break in the for loop


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 am trying to do like this:

$posts = Posts::find()->all();

foreach ($posts as $index => $post) {
    for($i = 0, $j = 0; $i < $index; $j++, $i++) {
        if ($j >= 4) {
          break;
        }
        $item = new PostAuthor();
        $item->setAttribute('post_id', $posts->id);
        $item->setAttribute('author_id', $j + 1);
        $item->save();
    }
}

Or:

$posts = Posts::find()->all();

foreach ($posts as $index => $post) {
    for($i = 0; $i < $index && $i < 4; $i++) {
        $item = new PostAuthor();
        $item->setAttribute('post_id', $posts->id);
        $item->setAttribute('author_id', $i + 1);
        $item->save();
    }
}

But I get the same, only when j reaches 4, the cycle does not start again, and it adds everything else from 1 to 4:

enter image description here

Is it possible to make the loop start over for the post IDs I'm circling in the screenshot?

In idea my table should look like this

enter image description here


Solution

  • $posts = Posts::find()->all();
    $authors = [1,2,3,4]; //ids of the authors
    $i = 1;
    foreach($posts as $post){
      $postAuthors = array_slice($authors, 0, $i);
      $post->authors()->sync($postAuthors); //I assume your relation is belongsToMany(), otherwise you can foreach $postAuthors to create PostAuthor
      $i++;
      //you can use $i+=rand(1,4) instead to add more randomness
      if($i>4){
        $i=0; //settings to 0 will produce each 5 post to not have authors. If you set to 1 all posts will have author
      }
    }
    

    For each post we take N authors, sync relation then reset counter