Answer has many rates:
Answer Model:
public function rates()
{
return $this->hasMany('App\Rate');
}
Rates table:
id answer_id user_id rating
1 3 1 5
2 3 2 8
How do i get the specific answer with sum of rating?
From your question, you have two classes Answer and Rate. Also, there is hasMany relationship from Answer to Rate named 'rates'.
So for the sum of ratings of a specific answer, you can call 'sum' method from 'rates' relationship on 'Answer' model.
$answer = App\Answer::find(1);
$sum_of_rating = $answer->rates->sum('rating');
Related
I have 2 tables, 'Invoice table', and related 'linesInvoice' table.
To simplify it, I will say that the invoice lines table has only the invoice_id field for the relationship and total for the price.
Now, I need to get last invoices, with his totals (totals, is the sum of column 'total' in every line).
I've tried many examples, but none works for me correctly.
Controller:
$lastInvoices = Invoice::latest()
->limit(10)
->with(['invoiceLines'])->get();
Model for relation
public function invoiceLines()
{
return $this->hasMany(InvoiceLines::class, 'invoice_id');
}
The result that I want for example looks like:
[
Invoice_id => 1
total => 500 //Sum of totals in lines of invoice 1
],
[
Invoice_id => 2
total => 300 //Sum of totals in lines of invoice 2
],
I guess I could go through all the invoices and lines in foreachs and make the sum. But I hope it can be done in the same query
You can use withSum method. This method accept the relation method as first argument and column to sum as second argument
$lastInvoices = Invoice::latest()
->limit(10)
->withSum('invoiceLines','your_column_name')
->with(['invoiceLines'])->get();
Laravel 8^
Invoice::with('invoiceLines')->latest()->first()->invoiceLines()->sum('totle');
totle colme table invoiceLines
In eloquent : How to get related a model where count of related models with a condition is is exactly n?
Here is over simplification of the problem that I am facing:-
There are multiple courses in database.
One course has many students.
I need to get courses with exactly 20 female students.
So, I need to do both.
Check that count of number of students is 20.
And check the condition that they are female.
Now I can either use "wherehas" which does not let me count related students. In fact it only checks if there is at least one female student.
Course
::whereHas('students',function($q){
$q->where('gender','Female');
})
->get()
;
Or I can use "has" which lets me count the related students but does not let me check if they are female or not.
Course
::has('students','=','20')
->get()
;
I need something that allows me to do both checking the count of students and checking that they are all female. Something like this is needed:-
// NOT ALLOWED IN ELOQUENT
Course
::has('students','=','20',function($q){
$q->where('gender','Female');
})
->get()
;
What to do?
Per the Eloquent Relationships Documentation you can do something like this:
Course
::whereHas('students',function($q){
$q->where('gender','Female');
}, '=', 20)
->get()
I have the following models: User, Order, OrderPayment
whereby each user has many orders, and each order has many order payments.
The orderPayment model has the attribute "total_paid"
I would like to get the sum of the user's total paid for all his orders.
eg:
user has 3 orders.
the first order has the two following payment records: 5$ and 4$.
the second order has one payment of 10$
the third order has two payment records of 1$ and 4$
the total sum i want is 5 + 4+ 10+ 1+ 4 = 24$.
I have tried the following but it's not working at all :
$user->orders->orderpayment->sum('total_paid');
but i get this error
Property [orderPayment] does not exist on this collection instance
Since you want to sum values from the OrderPayment model, it is easier to start there. Try to write it like this:
OrderPayment::whereHas('order.user', function($query) use ($userId) {
$query->whereId($userId);
})->sum('total_paid');
Make sure all the relations are defined well.
Try:
$user->orders->orderpayment()->sum('total_paid');
I have 2 models; Post and Rating
The Rating model contains an amount column which specifies how high something has been rated. This is based on 5 star rating so the amount can be a value from 1-5
The Post model has a one to many relation with the rating model and function called Ratings that returns the hasMany.
I'd like to get the 5 latest posts based on the average rating. For the average rating I've created a function that can be seen below
Note: the plural(Ratings) returns the hasMany relation where as the singular(Rating) returns a value which is the average rating
public function Rating(){
return floor($this->Ratings()->avg('rating'));
}
Is it possible to retrieve posts ordered by the avg rating using the Eloquent QueryBuilder?
Currently I'm retrieving all posts and then using the sortBy method on the collection object in order get the ones with the highest average rating. The way I'm doing this can be seen below.
$posts = Post::all();
$posts = $posts->sortByDesc(function ($post, $key) {
return $post->Rating();
});
Now if I'd only want to show 5 I still have to retrieve and sort everything which doesn't seem very resource friendly(In my eyes. I don't have any proof of this or say it is true).
So my question is the following: Is this doable using Eloquent instead of sorting the FULL collection.
Sub question: Will doing this with Eloquent instead of sorting the collection have any impact on efficiency?
You may use query builder
DB::table('post')
->select('post.id', 'AVG(rating.amount)')
->join('rating', 'post.id', '=', 'rating.post_id')
->groupBy('post.id')
->orderByRaw('AVG(rating.amount) DESC');
I am having a hard time figuring this out in laravel; for a subscriber relationship we have 2 pivot tables:
A subscriber can subscribe to a question:
question_subscriber
id question_id subscriber_id
1 2 3
2 2 4
3 3 1
4 3 2
A subscriber can subscribe to a user:
user_subscriber
id user_id subscriber_id
1 1 6
2 1 7
3 2 1
Normal questions table with question owner:
questions
id question user_id
1 abc? 1
2 xyz? 1
3 123? 2
The pivot relationships are setup correctly in their models, and I can pull out with a foreach, subscribers for a question, $question->subscribersQuestion as $subscriber, or subscribers for a user, $user->subscribersUser as $subscriber:
But how can we pull out all subscribers that belong to a user (directly or indirectly (through a question they own))?
For example, these should be all retrieved subscribers for user 1:
6 // subscribed to directly
7 // subscribed to directly
3 // subscribed to through question
4 // subscribed to through question
Any idea on the most efficient way to do this in Laravel?
This will be the easiest way:
// assuming this setup:
User hasMany Question
User belongsToMany User (subscribers - direct)
Question belongsToMany User (subscribers - indirect)
// we don't need this, since we pass it by reference to the closure,
// but for clarity let's initialize this variable:
$indirectSubscribers = null;
$user = User::with(['questions.subscribers' => function ($q) use (&$indirectSubscribers) {
// get all indirect subscribers (cost of additional query)
$indirectSubscribers = $q->get()->unique();
}])->find($userId);
// merge with directs subscribers
$allSubscribers = $user->subscribers->merge($indirectSubscribers);