0

I tried sum nested related column but get empty result.

Code:

$data = CropType::with(['categories' => function($cq) {
    return $cq->with(['varieties' => function($vq) {
        return $vq->with(['products' => function($pq) {
            return $pq->sum('total');
        }]);
    }]);
}])->get();

As you can see, I have 4 tables that are interconnected with foreign keys

  • Table: crop_types

    id

    title

  • Table: categories

    id

    title

    crop_type_id

  • Table: varieties

    id

    title

    category_id

  • Table: products

    id

    title

    total

    variety_id

But when I run my query it's run as like this instead summing total products:

"select * from crop_types"

How I can correctly sum total products in each crop type?

1
  • check this Commented May 15, 2021 at 10:00

1 Answer 1

1

Try this query to get total products in each crop type:

SQL

SELECT crop_types.id,
         crop_types.title AS title,
         sum(products.total) AS total
FROM `products`
INNER JOIN `varieties`
    ON `varieties`.`id` = `products`.`variety_id`
INNER JOIN `categories`
    ON `categories`.`id` = `varieties`.`category_id`
INNER JOIN `crop_types`
    ON `crop_types`.`id` = `categories`.`crop_type_id`
GROUP BY  `crop_types`.`id`

Laravel Eloquent

$result = Product::query()
    ->selectRaw('crop_types.id, crop_types.title as title, sum(products.total) as total')
    ->join(
        'varieties',
        'varieties.id',
        '=',
        'products.variety_id'
    )
    ->join(
        'categories',
        'categories.id',
        '=',
        'varieties.category_id'
    )
    ->join(
        'crop_types',
        'crop_types.id',
        '=',
        'categories.crop_type_id'
    )
    ->groupBy('crop_types.id')
    ->get();
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.