I have a polymorphic relation on my Item Table
public function categories(): MorphToMany
{
return $this->morphToMany(Category::class, 'categorizable', 'categorizables', 'categorizable_id', 'category_id')
->withTimestamps();
}
It works. I get a list of objects as expected. Only, some models in my database will always have only one category.
I’d like to avoid getting a list of items. I would like the object directly.
I tried that, but it doesn't work :
public function category()
{
return $this->morphToMany(Category::class, 'categorizable', 'categorizables', 'categorizable_id', 'category_id')->first;
}
Call to undefined method App\Models\Category::addEagerConstraints()
I have a result like that :
{
'id': 1,
'name': 'My name',
'categories': [
{my object category}
]
}
I want :
{
'id': 1,
'name': 'My name',
'category':
{my object category}
}
How can I do this? It's a many to many polymorphic relationship.