You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在迁移循环中限制author_id最大值为4并循环重置?

问题与解决方案

问题背景

我有一个模型及数据表的现成数据,已在该模型中新增字段并与另一张表建立关联。为避免手动为每条记录填充该字段,计划创建迁移自动填充。关联表包含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();
    }
}

当前逻辑下,author_id的最大值等于帖子数量,例如第一篇帖子对应author_id:1,第二篇对应author_id:1和2,以此类推最多到6。需要调整逻辑,使author_id最大值为4,达到4后从1重新开始循环。

修正后的代码

首先修正原代码中的错误($posts->id应为$post->id),然后通过取余运算实现author_id的1-4循环:

$posts = Posts::find()->all();
$maxAuthorId = 4; // 设定author_id的上限值

foreach ($posts as $index => $post) {
    for($i = 0; $i < $index; $i++ ) {
        $item = new PostAuthor();
        $item->setAttribute('post_id', $post->id); // 修正原代码的对象调用错误
        // 取余运算实现循环:(i % 4)得到0-3,加1后转为1-4
        $authorId = ($i % $maxAuthorId) + 1;
        $item->setAttribute('author_id', $authorId);
        $item->save();
    }
}

迁移场景优化建议

如果是在迁移文件中执行数据填充,建议使用数据库查询构建器替代模型操作,避免模型事件干扰:

use Illuminate\Support\Facades\DB;

$posts = DB::table('posts')->get();
$maxAuthorId = 4;

foreach ($posts as $index => $post) {
    for($i = 0; $i < $index; $i++ ) {
        DB::table('post_authors')->insert([
            'post_id' => $post->id,
            'author_id' => ($i % $maxAuthorId) + 1
        ]);
    }
}

逻辑说明

取余运算$i % $maxAuthorId会返回0到3的结果,加1后刚好得到1-4的循环序列:

  • 当i=0时,0%4+1=1
  • 当i=3时,3%4+1=4
  • 当i=4时,4%4+1=1
  • 后续以此类推,完美实现"到4后从1重新开始"的需求。

内容的提问来源于stack exchange,提问作者broken heart

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.31 10:25:17