On my website I allow users to upload images/like images/favorite images/etc.
Therefore, I've got a table for images, likes, favorites, etc.
I can get and display these images just fine, and sort them as I like
$images = Images::orderBy('id', 'desc')->Paginate(50);
I can also display how much likes/favorites an image has.
$favCount = Favorite::where('image_id', $image->id)->count();
However, what would I do to sort images by, say, how many favorites it they have? I have a favorite model and an image model but I'm not sure how I would go about it.
EDIT:
Current query for the answer given:
$images = Images::join('favorites', 'favorites.image_id', '=', 'images.id')
->select('images.link', DB::raw('count(favorites.id) as favs'))
->orderBy('favs', 'desc')
->groupBy('images.link')
->take(10)
->get();
And the error is:
SQLSTATE[42S22]: Column not found: 1054 Unknown column 'images' in 'field list' (SQL: select
images
, count(favorites.id) as favs fromimages
inner joinfavorites
onfavorites
.image_id
=images
.id
group byimages
.link
order byfavs
desc limit 10)
DB
as I did? I think the error comes fromImages::raw()
. Try replacingImages::raw
byDB::raw()
. Or do all the query withDB
as I did. And see the results. Please. – EddyTheDoveimages
if you have a propertylink
orname
. Tryselect('link', DB::raw('count(favorites.id) as favs'))
. It seems you don't have propertyimages
in your tableimages
. Can you try it all withDB
as I did and see if it works ? – EddyTheDove