我有两个表categories
和product_categories
。
categories
具有id
,name
和product_categories
具有category_id
。如何从id
获取categories
并将其值放入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);
}
答案 0 :(得分:1)
在使用类别属性之前保存类别。
foreach($categories as $category) {
$categories = new Category;
$categories->name = $category;
$categories->save();
$productCategories = new ProductCategory;
$productCategories ->category_id = $categories->id;
$productCategories->save();
}