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

293
Visualizações
How to get join results as an array of objects in Laravel?

I have been working on a personal project where users can rate different shops. Among many, I have two tables schemas that I am working on.

Table: Shops

  1. id
  2. shop_name
  3. user_id (shops belongs to a user)

Table : Ratings

  1. id
  2. shop_id (foreign_key)
  3. rating
  4. user_id

Now I want to fetch all the shops and its corresponding ratings using SQL join.

 $shop = Shop::leftJoin('ratings', 'ratings.shop_id', '=', 'shops.id')
    ->select('shops.*', 'ratings.rating')->get();
    return response($shop);

When I do this I get response but the it is repeated for each ratings on the same shop.

[
    {
        "id": 1,
        "name": "manjil",
        "rating": 4
    },
    {
        "id": 1,
        "name": "manjil",
        "rating": 5
    },
    {
        "id": 1,
        "name": "manjil",
        "rating": 2
    }]

What I really want is :

        [{
            "id": 1,
            "name": "manjil",
            "rating": [4,5,2]
        }]

Please Laravel geeks, help :)

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

0

the easy solution would be to use the relation directly

$shops = Shop::with('ratings')->get();
//possible mapping here
return response($shops);

you can afterwards map the ratings to get only an array of the field rating

$shops = $shops->map(function ($shop) {
    $shop->ratings = $shop->ratings->pluck('rating')->all();
    return $shop;
});
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