I need your help.
I have next models:
class Store extends Model {
public function categories()
{
return $this->belongsToMany(Category::class,'category_by_store','store_id','category_id')->withPivot('refIdInMyStore');
}
}
class Category extends Model{
public function store()
{
return $this->belongsToMany(Store::class, 'category_by_store','category_id','store_id');
}}
So, if I want to retrieve categories from a store I write:
$store = Store::find(1);
$categories = $store->categories()
But the response is: {"withTimestamps":false}
¿What is my mistake?
Thanks!
It's because you are calling it as a function $store->categories()
. Which would be similar to calling Categories::where('store_id', $id)
without calling ->get()
to execute the query.
You should call it as an attribute $categories = $store->categories
instead.
There are many who are against not being explicit about the fact that you are executing a new query because the relationship looks like an attribute.
I have found that it's better for code clarity and likely performance to use the eager loading like this:
$store = Store::with('categories')->find(1);
I believe this clearly signals that you will be using the categories relationship.