Answer the question
In order to leave comments, you need to log in
How to execute such sql query in laravel 5.3?
SELECT sum(likes.like)
FROM places left OUTER JOIN media_items ON places.id = media_items.place_id
left OUTER JOIN likes ON media_items.id = likes.likeable_id
WHERE likes.likeable_type = 'App\\MediaItem'
AND places.id = 1;
public function getRatingAttribute()
{
$sql = "SELECT sum(likes.like)
FROM places left OUTER JOIN media_items ON places.id = media_items.place_id
left OUTER JOIN likes ON media_items.id = likes.likeable_id
WHERE likes.likeable_type = 'App\\MediaItem'
AND places.id = 1;";
$result = DB::connection()->getPdo()->exec($sql);
return $result;
}
public function getRatingAttribute()
{
$mediaItems = $this->mediaItems;
$result = 0;
$result += $this->likes->sum('like');
foreach ($mediaItems as $mediaItem) {
$result += $mediaItem->likes->sum('like');
}
return $result;
}
Answer the question
In order to leave comments, you need to log in
To begin with, it is worth deciding what task you need to solve: How else can you write a query? How to write it with "more standard Laravel functionality"? Or how to make it faster? Or how to make fewer requests?
Based on these answers, you need to build a different solution.
If you don't like ->exec(), then you can wrap it in DB::raw.
Your "original" solution can be rewritten via lazy load
$mediaItems = $this->mediaItems;
$mediaItems->load('likes')
$result = 0;
$result += $this->likes->sum('like');
foreach ($mediaItems as $mediaItem) {
$result += $mediaItem->likes->sum('like');
}
return $result;
SELECT like
FROM reports_likes
WHERE type = 'App\\MediaItem'
AND place_id = 1;
Why are raw expressions from the documentation not suitable?
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question