I wanna get all articles with votes

Published 1 month ago by SmokeTM

I try to get all articles with a certain amount of votes. In this case 5. Someone knows how to do that?

  $articles = Article::with('user', 'categorie', 'comments', 'votes')
            ->withCount('votes', 'cryptoVotes')
            ->where('created_at', '<=', Carbon::now()->subHour(1))
            ->where('sum(crypto_votes_count)', '>', 5)
            ->paginate(20);
Best Answer (As Selected By SmokeTM)
Vilfago

It depends how you stored it, but you can try

$articles = 
Article::with('user', 'categorie', 'comments', 'votes')
    ->has('votes', '>=', 5)
    ->where('created_at', '<=', Carbon::now()->subHour(1))
    ->paginate(20);

//or

$articles = 
Article::with('user', 'categorie', 'comments', 'votes')
    ->has('cryptoVotes', '>=', 5)
    ->where('created_at', '<=', Carbon::now()->subHour(1))
    ->paginate(20);

https://laravel.com/docs/5.5/eloquent-relationships#querying-relationship-existence

Cinek
Cinek
1 month ago (24,960 XP)

Try this

 $articles = Article::with('user', 'categorie', 'comments', 'votes')
            ->withCount('votes', 'cryptoVotes')
            ->where('created_at', '<=', Carbon::now()->subHour(1))
            ->has('crypto_votes_count', '>', 5)
            ->paginate(20);
SmokeTM

Tried that but it throws "Method Illuminate\Database\Query\Builder::crypto_votes_count does not exist." exception. If I dd($articles) without the ->has Querie there is a crypto_votes_count attribute!

Cronix
Cronix
1 month ago (794,690 XP)

It would be having(), not has(). Has() is for relationships.

SmokeTM

The same tried that already. I get Unknown column 'crypto_votes_count' in 'having

Vilfago

It depends how you stored it, but you can try

$articles = 
Article::with('user', 'categorie', 'comments', 'votes')
    ->has('votes', '>=', 5)
    ->where('created_at', '<=', Carbon::now()->subHour(1))
    ->paginate(20);

//or

$articles = 
Article::with('user', 'categorie', 'comments', 'votes')
    ->has('cryptoVotes', '>=', 5)
    ->where('created_at', '<=', Carbon::now()->subHour(1))
    ->paginate(20);

https://laravel.com/docs/5.5/eloquent-relationships#querying-relationship-existence

Cronix
Cronix
1 month ago (794,690 XP)

try cryptoVotes_count since your relationship apparently is named cryptoVotes.

Please sign in or create an account to participate in this conversation.