Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

258
Views
Laravel raw query and including model relations

I am trying to return a single post with a sub-query to include a count of down-votes and up-votes. I am able to achieve this by using a raw query.

However doing so means that I can no longer access the post models relations e.g. comments.

Is there more of an Eloquent way I can do this to keep the models relations?

Or is there a better way I could be going about the whole thing? Would love to hear how you would go about it.

$post = DB::select(
        "SELECT post.*, 
        (SELECT COUNT(*) FROM posts_votes 
        WHERE type = 1 
        AND post_id = posts.id) 
        AS up_votes, 
        (SELECT COUNT(*) FROM posts_votes 
        WHERE type = 2 
        AND post_id = posts.id) 
        AS down_votes 
        FROM posts 
        INNER JOIN posts_votes ON posts.id = posts_votes.post_id
        WHERE posts.id = ?", [$id])[0];
about 4 years ago · Santiago Trujillo
2 answers
Answer question

0

This is an old question, but it's the first result I get when I google "laravel relation raw query", so it might be useful for other people that are searching the same thing.

I managed to solve it like this:

$query = ""; //raw query goes here
$result = Model::fromQuery($query);
$result->load('relationship');

Make sure your custom raw query contains the proper columns specified in the model, otherwise the relationship will always return null.

Tested on Laravel 6.17.0

about 4 years ago · Santiago Trujillo Report

0

Try this

Post::select('*')
->addSelect(DB::raw('
    (select count(*) 
    from posts_votes 
    where type = 1 
    and post_id = posts.id) 
    as up_votes
'))
->addSelect(DB::raw('
    (select count(*) 
    from posts_votes 
    where type = 2 
    and post_id = posts.id) 
    as down_votes
'))
->whereIn('id', $ids)
->get();
about 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!