mysqllaraveleloquent

Laravel Eloquent Query - limit on a count()


I need to know if a table has more than 50 rows fitting some criteria. So, the raw query should look like this:

SELECT COUNT(id) FROM (SELECT id FROM table WHERE {conditions} LIMIT 50)

but I'm having trouble doing this through eloquent. This is what I've tried so far....

card::where( ... )->limit(50)->count("id");

... but this doesn't work. It doesn't make the subquery for the limit, so the limit becomes useless.

Without running a subquery that is limited, the query takes up to 10 times longer..... I'm afraid it won't be as scalable as I need.


Solution

  • I did eventually come up with a solution to this, I just didn't post it (until now). You can just grab the ID of the 50th record to see if it exists:

    $atLeastFifty = Card::offset(50)->value("id");
    
    if(!empty($atLeastFifty)){
        // there are at least 50 records
    }else{
        // there are less than 50 records
    }
    

    This is way faster than a count() when there are tons of records in the table.