PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Friday, October 21, 2022

[FIXED] how to use groupBy in hasMany relation in Laravel

 October 21, 2022     group-by, has-many, laravel, php     No comments   

Issue

I have 2 tables that are named Resort and booking. in the booking table, there is a field named amount. I want to join these tables using with hasMany relation and get sum of the amount field in the booking table using with groupBy. can you please help me to solve this problem?

Thanks in Advance


Solution

Laravel Eloquent has the own withSum() method for avoiding "groupBy()" method.

For your case you can use something like this (you can modify for your needs):

// resorts with bookings and their summary prices
$data = Resort::select([
    'id',
    'name',
    'image',
])
    // ->orderBy('some_field', 'ASC')
    ->with(['bookings' => function($query) {
        return $query->select([
            'id',
            'booking_id',
            'price',
        ]);
    }])
    ->withSum('bookings', 'price')
    // ->where('resorts.some_field', '<=', 123)
    ->get();
    // ->toArray();

But don't forget to have appropriate relation defined in your parent (Resort) model:

public function bookings() {
    return $this->hasMany(Booking::class, 'resort_id', 'id');
}

Also you need to have "resort_id" foreign key defined in child's (Booking) migration:

$table->unsignedTinyInteger('resort_id')->nullable();
$table->foreign('resort_id')->references('id')
    ->on('resorts'); // ->onUpdate('cascade')->onDelete('cascade');


Answered By - boolfalse
Answer Checked By - Robin (PHPFixing Admin)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing