从一个表到另一个表的Laravel插入ID

我有两张桌子categoriesproduct_categories

categoriesidnameproduct_categoriescategory_id。如何从categories中获取id并将该值放入category_id

我试过了:

Route::get('/categories/create', function() {
    $categories = [
        'Hardwares', 
        'Buldings',
        'Properties',
    ];

    foreach($categories as $category) {
        $productCategories = new ProductCategory;
        $categories = new Category;
        $categories->name = $category;
        $productCategories->category_id = $categories->id;
        $categories->save();
        $productCategories->save();
    }
}); 

可以通过一对一的关系吗?我刚刚在‘ProductCategory.php’中尝试了一下:

public function category() {
    return $this->belongsTo(Category::class);
}

转载请注明出处:http://www.cshftz.com/article/20230526/1806569.html