How to sum of column in laravel with relationship - laravel

How to sum of duration column where my course id or section id is same

Try this code:
$res = Model::groupBy('course_id', 'section_id')
->selectRaw('sum(duration) as total_duration, course_id, section_id') // do the sum query here
->pluck('total_duration','course_id', 'section_id'); // get the related query column here
Source answer

You have to use hasMany relation on this table with course and section table.
For hasMany relation see this docs. Here
Then, you can use foreach to generate the sum.
$summation = $yourtablenames->sum(function ($yourtablename) {
return $yourtablename->your_relation_name->sum('duration');
});

Related

Search in belongsToMany-relation for item by pivot value

I got these models:
Order
Invoice
An Order can have many Invoices and an Invoice can belong to many Orders.
Example:
Orders:
Order #1
Order #2
Order #3
Invoices:
Invoice #1 -> belongs To Order #1 and Order #2 (so this Invoice contains both Orders)
Invoice #2 -> belongsTo Order #2 and Order #3
Each belongsTo-relation saves a date as pivot, which defines the last date this order has been invoiced.
Now I'd like to create a isInvoiceable() getter for my Order-Model, which returns, whether the order has been invoiced within the last month or not. If the latest date is older than one month, return true, as this Order should create a new invoice.
So now I need your help: I need to check all invoices, whether there's an Order (belongsToMany) with the order_id of the current Order, and a date-pivot that's older than now - one month. I need to check the order_id because the Invoice could possibly contain information about other Orders, too.
And this is the missing link for me: How can I check the belongsToMany-relation in Invoice for date and order_id?
Asuming you have defined your relation as 'invoices', you may do something like this:
class Order extends Model {
...
public function isInvoiceable(){
$lastInvoiceDate = (date('Y-m-d', $this->invoices()->latest()->created_at));
$today = new Carbon(date('Y-m-d', strtotime(Input::get('startdate'))));
$diff_months = $lastInvoiceDate->diff($today)->months;
return $diff_months < 1;
}
There is a wherePivot method, which should do what you want.
From the docs:
Filtering Relationships Via Intermediate Table Columns:
You can also filter the results returned by belongsToMany using the
wherePivot, wherePivotIn, and wherePivotNotIn methods when defining
the relationship:
return $this->belongsToMany('App\Role')->wherePivot('approved', 1);
return $this->belongsToMany('App\Role')->wherePivotIn('priority', [1, 2]);
return $this->belongsToMany('App\Role')->wherePivotNotIn('priority', [1, 2]);
I have not tested it, but you should be able to do something like this:
public function isInvoiceable()
{
// replace 'invoices()' with your relationship
if ($this->invoices()->wherePivot('date', '>=', Carbon::now()->subMonth())->count() > 0) {
return false;
}
return true;
}
you have two choices:
1- like Remul said in his answer: using wherePivot();
2- using newPivotQuery()
witch give you more space to work with ...
when you use this method, the query will be on pivot table directly ...
class Order extends Model {
public function isInvoiceable()
{
return $this->invoices()-> newPivotQuery()->firstWhere('date', '>=', Carbon::now()->subMonth())!=null;
}
the advantage of using newPivotQuery() that you can insert,update, make overall queries ...

How can I get specific column fields?

I want return specific columns for every card that is returned by eloquent relationship.
I can do it with ->get(['column1', 'column2']) but in this situation I can't use get().
Is there a solution for this ?
$deckId = $request->deckId;
$deck = Deck::find($deckId);
return $deck->cards;
on the cards I want for example just the id the name and the card_type
This code should work if you already defined the relationship
return $deck->cards()->get(['id', 'name', 'card_type']);
Have you looked into pluck?
Deck::all()->pluck('column1', 'column2');
This will return an array with column1 as key and column2 as value

Laravel Query Builder max function and relationships

this code
$maxsub = Invoice::with(['userinvoicesubaccount'])->where([['person_id',$id]])->get();
#foreach($maxsub as $max)
{{$max->userinvoicesubaccount->subaccount_name}} </font></div>
#endforeach
Get me all subaccount's names related to my list of Invoices with a predefined ID.
What i need is to get the only subaccount name related to my list of invoices with the highest amount (that existe in my invoice table) with a predefined ID.
Any help ? thank you
First calculate the invoice with the highest amount like so:
$maxInvoice = Invoice::with('userinvoicesubaccount')->where('person_id',$id)
->orderBy('amount', 'desc')->first();
Then get the related sub accounts for that invoice like so:
$maxInvoice->userinvoicesubaccount
You can add a subquery to your with function.
$invoices = Invoice::with(['userinvoicesubaccount' => function($query) {
$query->max('amount'); // Max function gives you highest value of a given column
}])
->where([['person_id', $id]])
->get();
#foreach($invoices as $invoice)
// You will still need to call first because you will have a collection
{{$invoice->first()->userinvoicesubaccount->subaccount_name}} </font></div>
#endforeach
Take a look at https://laravel.com/docs/5.7/eloquent-relationships#eager-loading

Updating a pivot table in Eloquent

I've got a many to many relationship between a student and an institution_contact.
students should only ever have two institution_contacts and I have an attribute on the pivot table named type to be set as 1 or 2.
So, my pivot table looks like this:
institution_contact_student: id, institution_contact_id, student_id, type
I've run into difficulty in deciding how to approach the issue of adding/updating the pivot table. Let's say I have 100 students and I want to assign them a contact with the type of 1.
My current solution is to delete the contact then add it:
$students = Student::all(); // the 100 students
$contactId = InstitutionContact::first()->id; // the contact
foreach ($students as $student) {
// remove existing contact
$student
->institutionContacts()
->newPivotStatement()
->where('type', 1)
->delete();
// add new contact
$student
->institutionContacts()
->attach([$contactId => ['type' => 1]]);
}
However, I'm thinking that this is going to hit the database twice for each student, right? So would I be better off creating a model for the pivot table and removing all entries that matched the student id and the type then simply adding the new ones? Or would creating a model for the pivot table be considered bad practice and is there a better way of accomplishing this that I've missed?
Please note the reason I'm not using sync is because I'm relying on the type attribute to maintain only two contacts per student. I'm not aware of a way to modify an existing pivot without causing issues to my two contacts per student requirement.
Edit:
Instead of creating a model I could run the following code to perform the delete using DB.
DB::table('institution_contact_student') // the pivot table
->whereIn('student_id', $studentIds)
->where('type', 1)
->delete();
If I have understood your question correctly then you can use the updateExistingPivot method for updating your pivot table.But first of course you have to define the pivot in your relationship. For instance,
public function institutionContacts(){
return $this->belongsToMany('institutionContact')->withPivot('type');
}
after this, all you have to do is use the following code:
$student
->institutionContacts()
->updateExistingPivot($contactId, ["type" => 1]);
Hope this helps.

Eloquent query: Retrieving data from two related models having Same column names

Following gives the list of ID's of SectionDetail Model while I need List of ID's of Section Model:
SectionDetail::with('section')->where('class_id', '=', Input::get('grade_id'))->lists('id');
Problem is both Models SectionDetail and Section has columns "ID".
How can I point to the ID of SectionDetail and Section Model in my Query
You can't do that this way, since there are 2 separate queries fetching SectionDetail and Section.
In order to get Section ids you need to query that model filtered by the relation constraint:
$gradeId = Input::get('grade_id');
// assuming sectionDetails is relation name on the Section model
$sectionsIds = Section::whereHas('sectionDetails', function ($q) use ($gradeId) {
$q->where('class_id', '=', $gradeId); // use prefixed column name in case it's ambiguous
})->lists('id');

Resources