简体   繁体   English

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

[英]Laravel Insert ID from one table to another

I have two tables categories and product_categories . 我有两个表categoriesproduct_categories

categories has id , name and product_categories has category_id . categoriesidnameproduct_categoriescategory_id How do I fetch id from categories and put that value to category_id ? 如何从categories获取id并将该值放入category_id

I tried: 我试过了:

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();
    }
}); 

Is it possible via one to one relationship? 是否可以通过一对一的关系? I just tried this in `ProductCategory.php': 我只是在`ProductCategory.php'中尝试过:

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

save the category before using its attribute .. 在使用类别属性之前保存类别。

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM