4
votes

Category Table

enter image description here

Product Table

enter image description here

I want to be create relationship with category tables ->id with Product table category_id suggest any idea for this relationship Array with integer column relationship

Controller

Products::with('category')->get();

Product Model

public function category() {
    return $this->hasMany(App\Models\Categories::class, 'id', 'category_id');
}

Category Model

public function product() {
    return $this->belongsTo(Products::class,'category_id', 'id');
}
2

2 Answers

3
votes

If you want this to work you should create a many to many relationship.

Starting off your database should look something like this: enter image description here

This way your products and categories are linked properly and if you want to add a new category to a product or the other way around you can just add the ids of both the category and the product to the category_product table.

Then for your relation methods, in your Product.php (model) you will get this relation method:

/**
 * @return BelongsToMany
 */
public function categories(): BelongsToMany
{
    return $this->belongsToMany(Category::class);
}

And in your Category.php (model):

/**
 * @return BelongsToMany
 */
public function products(): BelongsToMany
{
    return $this->belongsToMany(Product::class);
}

You can now get all categories of a product by using:

$product = Product::first();
$product->categories;

Just for some extra information. You can use your model to store the relations.

For example you would like to add category 1, 2, 3 to the product.

You can simply do:

$product = Product::first();
$product->categories()->sync([1, 2, 3]);
0
votes

This seems like a good case for a pivot table, but if for some reason you really need this schema, then maybe you could use a subquery.

Products::addSelect(['category' => Category::select('name')
    ->whereIn('id', 'destinations.category_id')
])->get();

You would have to see if this is available in your laravel version. https://github.com/laravel/framework/pull/29567

you can added as a scope if you want to have it as part of your model.

public function scopeWithCategories($query) 
{
    $query->addSelect(['category' => Category::select('name')
        ->whereIn('id', 'destinations.category_id')
    ]);
}