Axel
Axel

Reputation: 5111

Laravel Insert ID from one table to another

I have two tables categories and product_categories.

categories has id, name and product_categories has category_id. How do I fetch id from categories and put that value to 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':

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

Upvotes: 0

Views: 756

Answers (1)

Demonyowh
Demonyowh

Reputation: 1672

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

Upvotes: 1

Related Questions