Skip to content
Advertisement

Laravel Relationship with integer[] type of postgresql column

I have categories table and products table. in products table have category_id column type of integer[].

ex: {1,2,3}

.

And I need products list with category relation which categories.id exist products.category_id

I tried in model Product:

public function category()
{
    return $this->belongsTo(Category::class, DB::raw("ANY(category_id)"), 'id');
}

no get category is null.

Advertisement

Answer

I can’t relation but with attribute i can get categories

firstly cast category_id to array and

public function getCategoriesAttribute()
{
    return Category::whereIn('id',$this->category_id)->get();
}

and it works

User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement