Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

382
Visualizações
RelationShip BelongsToMany Laravel - Only return withTimeStamps

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!

over 4 years ago · Santiago Trujillo
1 Respostas
Responde à pergunta

0

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.

over 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda