Laravel将ID从一个表插入另一个表

时间:2018-07-31 06:27:22

标签: php laravel

我有两个表categoriesproduct_categories

categories具有idnameproduct_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);
}

1 个答案:

答案 0 :(得分:1)

在使用类别属性之前保存类别。

foreach($categories as $category) {
    $categories = new Category;
    $categories->name = $category;
    $categories->save();

    $productCategories = new ProductCategory;
    $productCategories ->category_id = $categories->id;
    $productCategories->save();
}