May 29, 2018
0
Level 4
Raw query
I have a polymorphic relation.
Class Reply
public function replyable()
{
return $this->morphTo();
}
Which belongs to User and Trainer.
When I fetch replies I want an authenticated user's reply placed first.
So, if an auth user is a trainer, trainer's reply should be first and an auth user is a normal user, user's reply should be first.
This is what I got for now.
public function index(Question $question)
{
if (!! trainer()) {
//if an auth user is a trainer, place their posts first in the response data
return $question->replies()->orderByRaw("FIELD(replyable_id, ".trainer()->id.") DESC")->inRandomOrder()->with('replyable', 'question')->paginate(15);
}
if (auth()->check()) {
//if an auth user is a normal user, place their posts first in the response data
return $question->replies()->orderByRaw("FIELD(replyable_id, ".auth()->id().") DESC")->inRandomOrder()->with('replyable', 'question')->paginate(15);
}
return $question->replies()->with('replyable', 'question')->inRandomOrder()->paginate(15);
}
I need to restraint a query based on replyable_type.
So, an auth user is a trainer, replies should be ordered first with a reply which has replyable_type of trainer with replyable_id of whatever the authenticated user (trainer) id is.
This query is not working.
if (!! trainer()) {
//if an auth user is a trainer, place their posts first in the response data
return $question->replies()->orderByRaw("where replyable_type = trainers FIELD(replyable_id, ".trainer()->id.") DESC")->inRandomOrder()->with('replyable', 'question')->paginate(15);
}
Please or to participate in this conversation.