每个循环中是否有任何问题可以打破它而不创建模型?

Is there any issue in each loop to break it and not create models?

请问下面的代码有什么问题吗,我试了好久也没找到答案。 我想在过滤 dom.

循环中的每次迭代中创建模型
$node->filter('div.panel-section.font-size-2.font-size-xxs-normal .row')->each(function (Crawler $nestedNode, $i) use (&$part) {
        $model_category = ModelCategory::firstOrCreate(['name' => $nestedNode->filter('.bold.mb-2 a')->first()->text()]);
        $part->modelCategories()->sync($model_category, false);
        $nestedNode->filter('.col-xs-6.col-md-3')->each(function (Crawler $columns, $i) use (&$model_category) {
             $model = Model::Create(['name' => $columns->filter('a')->first()->text()]);
             $model->category()->associate($model_category);
             $model->save();
        });
});

我在 Model 和 ModelCategory 之间有一对多的关系

我在查找和搜索后发现了问题。这是因为同步语法。 eloquent 关系中的同步函数获取 id 数组作为第一个参数,但我向它传递了一个对象。下面是更正后的代码:

$node->filter('div.panel-section.font-size-2.font-size-xxs-normal .row')->each(function (Crawler $nestedNode, $i) use (&$part) {
    $model_category = ModelCategory::firstOrCreate(['name' => $nestedNode->filter('.bold.mb-2 a')->first()->text()]);
    $part->modelCategories()->sync([$model_category->id], false);
    $nestedNode->filter('.col-xs-6.col-md-3')->each(function (Crawler $columns, $i) use (&$model_category) {
         $model = Model::Create(['name' => $columns->filter('a')->first()->text()]);
         $model->category()->associate($model_category);
         $model->save();
    });
});