Working with Eloquent, How to select popular comments - laravel

I am designer trying to learn coding here and Laravel is so great in that it enables design like me to be able to create something myself smile
On to my question, I followed some of tutorial and now I learn to build simple blog system.
So I have Post model that has relationship $this->morphMany('Like','likeable','likeable_type'); with Like model.
Everything works great so far. Now I want to be able to create 'Popular Posts' page that basically shows the posts ordered by popularity, which is number of likes in my case.
The 'likes' table has these field id | likable_id | likeable_type
'likeable_type', in this case, is 'Post'
'likeable_id' is the post id linked to id in 'posts' table
So in my controller, I tried this.
$popular_ids = DB::table('likes')
->select('likeable_id')
->groupBy('likeable_id')
->orderBy(DB::raw('COUNT(likeable_id)'), 'DESC')
->get();
$popular_posts = Post::whereIn('id',array_pluck($popular_ids,'likeable_id'))->paginate(15);
This gives me all the popular posts but not in the order that I want.
I'm not sure if there is better way to achieve this or it seems that I only miss another 'orderBy' method?
Any suggestion on this?
ps. Sorry for my poor English

SQL IN does not maintain order. To achieve this have to user ORDER BY FIELD('id', , ,...) to achieve this.
$ids = array_pluck($popular_ids,'likeable_id');
$raw = DB::raw('FIELD(id,' + implode(',', $ids) + ')');
$popular_posts = Post::whereIn('id', $ids)->orderBy($raw)->paginate(15);
For more information refer to,
Maintaining order in MySQL "IN" query

I would do this with a join. It's kinda complex but if you want to understand the internals you should read into LEFT JOIN and INNER JOIN. This example is particularly ugly because of the polymorphic relationship.
Post::select('posts.*', DB::raw('COUNT(DISTINCT likes.id) AS popularity'))
->leftJoin('likes', function ($join)
{
$join->on('likes.likeable_id', '=', 'posts.id')
->on('likes.likeable_type', '=', DB::raw("'Post'"));
})
->orderBy('popularity', 'DESC')
->paginate(15);
There is a bonus in that the popularity value is now available on the posts.
$post->popularity;

Thank you Collin for your time! Your answer leads me to the light!!! I modified your answer a bit and finally get what I need. I'm still trying to fully understand it though. This is what I ended up with.
Post::select('posts.*', DB::raw('COUNT(likes.likeable_id) AS popularity'))
->join('likes', function($join)
{
$join->on('likes.likeable_id', '=', 'posts.id')
->on('likes.likeable_type', '=', DB::raw("'Post'"));
})
->groupBy('likes.likeable_id')
->orderBy('popularity', 'DESC')
->paginate(15);
Ps. Even though this code gives me what I want, I'm not sure if I did my db design right.

Related

Struggle with how to get something from my database with Laravel

😄 Hi!
Sorry the title isn't that explicite, but I'm a beginner and I really don't have the vocabulary just yet 😶
I've been struggling for hours with something, so before I trow my computer by the window, I came to ask for help :3
In my database I have a table with exhibitors and an other one with labels for those exhibitors. It's a many to many relationship and on my Controller I get the exhibitors with they labels that way :
$exposants = Expo::where('this_year', 1)->with('labels')->get();
It's working great! But now I want more!
I need to get the Exhibitors with a specific label. Let's say I want the exhibitors who would come this year with they labels {that part I already have} but only those who have the column "name" on the "label" table equal to "food". How do I do that ? 😅
Please help my 🙏
You can try
$exposants = Expo::where('this_year', 1)
->whereHas('labels', fn($q) => $q->where('name', $request->input('labelName'))
->with('labels')
->get();
//OR using non-arrow closure for PHP 7.3 and lower
$exposants = Expo::where('this_year', 1)
->whereHas('labels', function($q) use($request){
$q->where('name', $request->input('labelName'));
})
->with('labels')
->get();
//replace labelName with whatever key you have on request
Laravel docs: https://laravel.com/docs/8.x/eloquent-relationships#querying-relationship-existence

How to use AND in laravel database query

$konten = Konten::all()->where('kategori','Announcement' AND 'kategori','Activities')->sortByDesc('id');
It's not work what is the right query for using AND Logic in query sir ? im so sorry i don't have much knowledge to find out the way.. the point is i want $konten contains the row from Konten where the kategori is Announcement and Activities.. how to make it happen ? it just showing konten where the kategori is activities the announcement not passed..
You can chain several where to achieve AND:
$konten = Konten::where('kategori', 'Announcement')
->where('kategori', 'Activities')
->orderBy('id', 'desc')
->get();
Or use whereIn like this:
$konten = Konten::whereIn('kategori', ['Announcement', 'Activities'])
->orderBy('id', 'desc')
->get();
To achieve an AND in Laravel, you simply chain ->where() calls:
$konten = Konten::where('kategori','Announcement')->where('kategori','Activities') ...
As a side note, Konten::all() returns a Collection, and is no longer database logic. You shouldn't call ::all() unless you specifically need every record in the database.
Refactor to the following:
$konten = Konten::where('kategori','Announcement')
->where('kategori','Activities')
->orderBy('id', 'desc')
->get();
This will leverage the database to perform the filtering/ordering, instead of offloading every record into a Collection and allowing PHP to perform the same logic, which can be incredibly inefficient depending on the number of records.
try this:
$konten = Konten::whereIn('kategori', ['Announcement', 'Activities'])->orderBy('id', 'desc')->get();
I have a strong feeling that you probably seek for 'orWhere' clause... If you want ALL records when kategori column equals 'Announcement' and all records when kategori equals 'Activities' you sholud use orWhere clause like so:
$konten = Konten::where('kategori', 'Announcement')
->orWhere('kategori', 'Activities')
->orderBy('id', 'desc')
->get();
Or as mentioned in answers below you can use whereIn statement.

Multiple inner joins using laravel and translation

I have problem using translatable library, I am trying to sort the companies by name, so as written in the doc, I need to use inner joins, I tried this code, everything is good but the data is messed up when I add voucher_translations, its like it get from different table or records, I dont know what I am doing wrong :(
$vouchers = Voucher::join('company_translations', 'vouchers.company_id', '=', 'company_translations.company_id')
->join('voucher_translations', 'voucher_translations.voucher_id', '=', 'vouchers.id')
->where('company_translations.locale', '=', 'en');
->where('voucher_translations.locale', '=', 'en')
->orderBy('company_translations.name', 'asc');

Laravel, Many-to-many relationships, find() vs where()

I have a Laravel 4.2 site with a pretty simple database layout. The important part is a People model and a Subject model that have a many-to-many relationship. This works, so that, for instance:
$id = 5;
$ppl = Subject::find($id)->people()->orderBy('lastname')->get();
Returns all People for a given Subject. What I'm trying to do is instead of finding all the People for a single subject, to find all the people for multiple subjects. My guess was something like this:
$subjects = array(5, 6, 7);
$ppl = Subject::whereIn('id', $subjects)->people()->orderBy('lastname')->get();
That doesn't work (undefined method people()). Neither does the following (undefined property people):
$ppl = Subject::whereIn('id', $subjects)->people->orderBy('lastname')->get();
I'm currently just using raw SQL t get around this. How can I use eloquent relationships with where() or whereIn() calls on a model? Or, is there just a better eloquent way of approaching this problem.
Edit: Here's the raw SQL I used to get a list of the people.id's for a given array of subjects:
SELECT
DISTINCT(people.id)
FROM people
LEFT JOIN person_subject ON person_subject.person_id=people.id
WHERE
person_subject.subject_id IN (%s) AND
deleted_at IS NULL
Your eloquent relationships should allow you to eagar load the people related to a subject, you can do something like this:
Subject::whereIn('id', $subjects)->with('people')->orderBy('lastname')->get();
This will return your people related to the subjects.
Let me know if this doesn't work.
What you need is to join the tables to order by the lastname:
$ppl = Subject::whereIn('id', $subjects)
->select('subjects.*')
->distinct()
->join('people', 'people.id', '=', 'subjects.people_id')
->orderBy('lastname')
->get();
Check all your tables names because I don't know them and above are just an example one.

How to add dynamic 'where' to eloquent ORM with() relation

I'm, trying to do something like this:
$verfuegbarkeiten = Verfuegbarkeit::verfuegbar()->with('product', 'producer', 'producer.user', 'producer.user.ort')->where('product.kategorie_id', '=', $_GET['kat'])->get()->toArray();
I want to use a 'where' clause so i can only get the results where the 'product's attribute 'kategorie_id' matches the GET parameter. How can I 'where' on a relation? It's really important to me that this value can be dynamic, so writing a fix function in the related Model won't be a good solution.
Every hint appreciated
You want whereHas(), documentation here: https://laravel.com/docs/5.2/eloquent-relationships#querying-relations
For your example, that would mean something like this:
$kat = $_GET['kat'];
$verfuegbarkeiten = Verfuegbarkeit::verfuegbar()
->with('product', 'producer', 'producer.user', 'producer.user.ort')
->whereHas('product', function($query) use ($kat) {
$query->where('kat', $kat);
})
->get()
->toArray();
Although I might add that using $_GET is generally discouraged in Laravel.

Resources