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

ahmadissa's avatar

Active results like Eloquent "with" in query builder

Hello, I'm trying to get database records as same as Eloquent "with" so

for example my query builder query return the following data

    $comments      = \DB::table('comments as T1')
                                  ->select('T1.product_id','rating')
                                  ->where('T1.shop_name', '=', "$shop")
                                  ->join('products as pr', 'pr.product_id', '=', 'T1.product_id')
                                  ->distinct()
                                  ->paginate(10, [ 'T1.product_id' ]);
data": [
{
"product_id": "465549557783",
"rating": 4
},
{
"product_id": "465549557783",
"rating": 5
},
{
"product_id": "465549557783",
"rating": 3
},
{
"product_id": "465549557783",
"rating": 2
},
{
"product_id": "465549557783",
"rating": 1
},
{
"product_id": "478759485463",
"rating": 5
},
{
"product_id": "478759485463",
"rating": 4
},
{
"product_id": "478759485463",
"rating": 3
}

but I want the id to be unique so how can I achieve a results like this one ?

data": [
{
"product_id": "465549557783",
    {
        "rating": 4,
        "rating": 5,
        "rating": 3,
        "rating": 2,
        "rating": 1,
    }
},
{
"product_id": "478759485463",
    {
        "rating": 5,
        "rating": 4,
        "rating": 3
    }
},

Is it possible ?

0 likes
4 replies
Snapey's avatar

If you want nested results like eloquent, why not use eloquent?

shez1983's avatar

you can certainly do something like:

$comments = collect($comments);

$comments->groupBy('product_id');

one other consideration is the fact you are paginating..it may not be a big deal but if i saw

data": [
{
"product_id": "465549557783",
    {
        "rating": 4,
        "rating": 5,
        "rating": 3,
        "rating": 2,
        "rating": 1,
    }
},
{
"product_id": "478759485463",
    {
        "rating": 5,
        "rating": 4,
        "rating": 3
    }
},

i would think 478759485463 only has three ratings but in actual fact it could have more but becuase its paginated we wont see them

ahmadissa's avatar

@Snapey because eloquent returns all data and I want the data that has relation only

@shez1983 I will try it and comeback

Thank you all for your time.

CrucialDev's avatar
Level 36

@ahmadissa You might try the "has("relationship")" method off your model. That will filter down to items that have that relation.

1 like

Please or to participate in this conversation.