限制 for 循环中条目的数量。

huangapple go评论50阅读模式
英文:

limit the number of entries in the for loop

问题

我有一个模型和一个包含数据的表。在这个模型中,我添加了一个新字段,并与另一个表建立了连接。

为了不需要手动为每个记录填写这些字段,我想创建一个迁移,以便自动为所有记录填写这个字段。

关系表有两个字段:post_id 和 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();
    }
}

现在一切都是最大的作者ID数量等于帖子的数量,即对于第一个帖子,它将是作者ID:1,对于第二个帖子,它将是作者ID:1和作者ID:2,依此类推,直到6个作者ID。

我可以限制 $index,以便这里的最大数是4,当作者ID达到4时,循环从1重新开始吗?

英文:

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?

答案1

得分: 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();
}
}

英文:
$posts = Posts::find()-&gt;all();

foreach ($posts as $index =&gt; $post) {
    for($i = 0; $j=0; $i &lt; $index; $i++ ) {
        if ( $j &gt; 4 ) {
        $j = 0;
        }
        $item = new PostAuthor();
        $item-&gt;setAttribute(&#39;post_id&#39;, $posts-&gt;id);
        $item-&gt;setAttribute(&#39;author_id&#39;, $j+1);
        $item-&gt;save();
    }
}

huangapple
  • 本文由 发表于 2023年2月19日 22:04:46
  • 转载请务必保留本文链接:https://go.coder-hub.com/75500669.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定