使用Laravel insert eloquent 后获取存储项的id

Get the id of the stored items after using Laravel insert eloquent

我使用 Laravel 插入 Eloquent 方法在数据库中存储了一个数组,如下所示:

$newTags = [
    [
        'name' => 'tag1'
    ],
    [
        'name' => 'tag2'
    ],
];

if (sizeof($newTags) > 0) {
    Tag::insert($newTags);
}

在那之后,有没有办法得到保存项目的id

使用这个,

$newTags = [
        [
            'name' => 'tag1'
        ],
        [
            'name' => 'tag2'
        ],
    ];

    if(count($newTags) > 0){
         $id = Tag::insertGetId($newTags);
    }

对于批量插入,没有用于获取插入 ID 的内置方法。您可以使用 foreach 循环逐个插入并使用 insertGetId 获取 ID 并将它们放入数组中。

$insertedIDs = [];
if (count($newTags) > 0) {
    foreach ($newTags as $newTag) {
        $insertedIDs[] = Tag::insertGetId($newTag);
    }
}