英文:
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()->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();
}
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论