Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

locopetey's avatar

Query help

I have two models and need some nested, query help. for brevity, let's say my tables look like this:

Cars

Model  | Colors
----------
Nissan | 1,3,5
Toyota | 1,4

Colors

Id  | Color
----------
1 | Blue
2 | Red
3 | Green
4 | White
5 | Black

I want to query all the cars and colors and output somehthing like:

{ "model": "Nissan", "colors": [ "blue", "green", "white ] }

etc...etc..

any help would be greatly appreciated

0 likes
3 replies
nfauchelle's avatar

@locopetey

You should use a many many relation.

Car many many Colors.

Then in your Car model you set a colors function which will have the relation in it.

Then in your code you can be like.

    $cars = Car::with('colors')->get();
    foreach($cars as $car) {
        echo  $car->model;
        foreach($car->colors as $color) {
            echo $color->name;
        }
    }

you get the drift
tykus's avatar

@locopetey you're not actually storing a comma-separated list of color id's in your cars table are you? If you are, you should remove this to a pivot table (the conventional name would be car_color) consisting of two columns car_id and color_id with one record per car/color combination. Then in each Model, create a belongsToMany relation so that you can interrogate the relationship:

Car.php

public function colors()
{
    return $this->belongsToMany(Color::class);
}

This will allow you to do as @nfauchelle states above. The reverse of the relationship is also possible; i.e. you can get all car models for a specific color:

Color.php

public function cars()
{
    return $this->belongsToMany(Car::class);
}

Please or to participate in this conversation.