how to use groupBy in hasMany relation in Laravel - php

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

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');

Related

Getting specific column in Laravel relation returning empty array

I want to get specific column from Model relation in Laravel, but the relation model returning empty array.
Eloquent Query
$medicines = Medicine::with(['weightage' => function($query) {
$query->select('name');
}])->get(['name', 'description']);
Medicine Modal
public function weightage()
{
return $this->hasMany('App\MedicineWeightage', 'medicine_id');
}
You always need to also select the primary and foreign keys of the table to make the relation work:
$medicines = Medicine::with(['weightage' => function($query) {
$query->select(['id', 'name', 'medicine_id']);
}])->get(['id', 'name', 'description']);

Laravel Eloquent: Relationships multiple have issue & Eloquent “select” method not working with using “with” method

I am try to made Eloquent: Relationships for three model. Please have a look on my code.
$account = Account::select(['id', 'is_sign_contract', 'restaurant_name', 'state', 'phone_no', 'email', 'one_time_pick_up', 'sign_contract_date', 'created_at', 'oil_on_hand', 'binsize'])
->with(['completedservice' => function($c) {
//$c->select('id');
}])
->with(['accountService' => function($q) {
$q->with(['serviceProvider' => function($qs) {
$qs->select('id', 'company_name');
}])->select('account_id', 'service_provider_id', 'service_id');
}])
->whereRaw($where)
->orderBy('id', 'ASC')->offset(54)->limit(1)->get();
if i remove that //$c->select('id'); select form above relation then i get data if i am using it display blank relationship block.
below image for response in last image whole function there
In short without select it works fine, but if I am using select then not working.
Laravel loads the relations after the first query is run. In order for it to attach the related model to the parent you need to select the foreign key on the related table so Laravel knows which model to attach the child to after the query is run.
The accountService works because ytou are selecting account_id on that model to attach it to Account and serviceProvider works because you are selecting id on serviceProvider as well as service_provider_id on accountService so after all queries are run Laravel knows which models get attached where.
Your query is not working because you are not selecting the account_id on the child model.
The following will work:
$account = Account::select(['id', 'is_sign_contract', 'restaurant_name', 'state', 'phone_no', 'email', 'one_time_pick_up', 'sign_contract_date', 'created_at', 'oil_on_hand', 'binsize'])
->with(['completedservice' => function($c) {
$c->select('id', 'account_id');
}])
->with(['accountService' => function($q) {
$q->with(['serviceProvider' => function($qs) {
$qs->select('id', 'company_name');
}])
->select('account_id', 'service_provider_id', 'service_id');
}])
->whereRaw($where)
->orderBy('id', 'ASC')->offset(54)->limit(1)->get();
You need to have the foreign key selected along with any other fields you wish to select. Without which you'll get an empty relationship. So it should be something similar to $c->select('id', 'account_id');

How OrderBy afterwards HasMany and BelongsTo Relationships

I created a relationship between the "Review, Games and Info" tables, unfortunately, though, the main table is Games, and he orders me all for Games, While I would like to order the ID of "review" table.
Models: Review
public function games()
{
return $this->hasMany('App\Models\Giochi', 'id_gioco', 'id');
}
Models: Giochi
public function review()
{
return $this->belongsTo('App\Models\Review', 'id', 'id_gioco');
}
public function infogiochi()
{
return $this->belongsTo('App\Models\InfoGiochi', 'id', 'id_gioco');
}
Models: InfoGiochi
public function games()
{
return $this->hasMany('App\Models\Giochi', 'id', 'id_gioco');
}
Controller:
$review = Giochi::with('Review','InfoGiochi')->orderBy('id','DESC')->get();
Here is a screenshot of my json:
How do I order content for review table IDs?
You have 2 options. You use a join and order in the sql statement or you order it after retrieving the results in the collection.
Using Join
Giochi::select('giocos.*')
->with('Review','InfoGiochi')
->leftJoin('reviews', 'reviews.id', '=', 'giocos.id_gioco')
->orderBy('reviews.id','DESC')
->get();
Sorting Collection
Giochi::with('Review','InfoGiochi')
->get()
->sortByDesc(function($giochi) {
return $giochi->review->id;
});
This would be the shortest version to sort on the collection:
Giochi::with('review')
->get()
->sortByDesc('review.id');
You can modify your relationship query when you fire it:
Giochi::with([
'Review' => function ($query) { return $query->orderBy('id','DESC'); },
'InfoGiochi'
])->orderBy('id','DESC');
You can try with a raw query or you can use ->orderBy() directly on review function.

Laravel 5.4 adding specific column in existing selected colum with with()

I'm having a problem with displaying results from my db using eloquent in laravel 5.4. I just want to specify a columns that I want to be in my results. So in my case the record is relation to another tables which I want also to specify a column that I need. Please check my eloquent:
return User::with(['images' => function($q){
$q->select('user_id as userId','image_name','url');
}])
->orderBy('id', 'asc')
->select(['id as userId','name','email'])
->paginate(10);
and here's my hasMany() relations in my model:
public function images(){
return $this->hasMany('Images', 'user_id', 'id');
}
The problem with this code the images are always null.
Any idea? Thanks in advance.
Give this a try:
return User::with(['images' => function($q){
$q->select('id', 'image_name','url');
}])
->orderBy('id', 'asc')
->select(['id','name','email'])
->paginate(10);
You need to select the relationship key for it to find results.

Laravel 5 pivot table issue

I'm not sure how to explain my problem but i'll give it a try.
I'm using Laravel 5 and i have 3 tables:
pages
languages
language_page
This is what my models look like:
Page model:
public function languages()
{
return $this->belongsToMany('App\Language', 'language_page')
->withPivot('title', 'content', 'slug', 'meta_title', 'meta_description')
->orderBy('main', 'desc');
}
Language Model:
public function pages()
{
return $this->belongsToMany('App\Page')
->withPivot('title', 'content', 'slug', 'meta_title', 'meta_description');
}
What i want to do return a record from the page table where language_id is a certain id, and where slug is a certain text.
This is what i got so far: EDIT:
Page::with(['languages' => function($q) use($language_id, $slug) {
$q->where('language_id', $language_id);
$q->wherePivot('slug', $slug);
}])
->first();
My problem: how can i add a where clause with the column slug (from the pivot table language_page) ?
i hope this makes any sense at all..
Eloquent's BelongsToMany class has a
wherePivot()
method that allows you applying WHERE clauses to pivot table directly, see:
https://github.com/laravel/framework/blob/5.1/src/Illuminate/Database/Eloquent/Relations/BelongsToMany.php#L111

Categories