3

I have three tables, one defining a many to many relationship between the other two.

table : collections

table : collection_question

table : questions

I am running this query to return the number of questions a collection has

$results = DB::table('collections')
    ->select(array(
        DB::raw('count(collection_question.question_id) as question_count'),
        'name',
        'description'
    ))->leftJoin(
        'collection_question', 
        'collections.id', 
        '=', 
        'collection_question.collection_id'
    )->where('question_count', '>', 1)
    ->orderBy('question_count', 'asc')
    ->get();

This works fine as the select query is not tampered with by the query builder.

When I swap out get() for count() however the query builder replaces my select clause with select count(*) as aggregate which is understandable, however I loose the binding to question_count in the process and a SQL exception is thrown.

I've looked through the source code for Illuminate\Database\Query\Builder to try and find a solution but other than manually executing the raw query with a custom count(*) alongside my other select clauses I'm at a bit of a loss.

Can anyone spot a solution to this?

1 Answer 1

1

Instead of calling count() on a Builder object, I've resorted to creating my own count expression in addition to any other select clauses on the query rather than replacing them.

// This is in a class that uses Illuminate\Database\Query\Expression the clone
// isn't necessary in most instances but for my case I needed to take a snapshot
// of the query in its current state and then manipulate it further.
$query = clone($query);

$query->addSelect(new Expression("count(*) as aggregate"));

$count = (int) $query->first()->aggregate;
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.