trajan
trajan

Reputation: 1173

Laravel Query Builder and "not unique table/alias" error

I have conditional code that joins a table depending on input params

    $content = Content::select('content.*');

    if (isset($filters['ruleNumber'])) {
        $content->join('violation', 'violation.content_id', '=', 'content.id')
                ->where('violation.rule_number', $filters['ruleNumber']);
    }

    if (isset($filters['unprocessed'])) {
        $content->join('violation', 'violation.content_id', '=', 'content.id')
                ->where('violation.status', 'pending');
    }

If both $filters['ruleNumber'] and $filters['unprocessed'] are due, it will result in a duplicate join query (i.e. "violation" is joined twice). I could keep track of my joins prior to calling join(), but I'd need to implement this logic wherever I use the query builder.

It seems odd that the framework doesn't support this out of the box, or am I missing something?

Upvotes: 0

Views: 669

Answers (1)

Gopal
Gopal

Reputation: 111

minor change i made.. try this it might be work

$content = Content::select('content.*');
if (isset($filters['ruleNumber']) || isset($filters['unprocessed'])){
    $content->join('violation', 'violation.content_id', '=', 'content.id')
}

if (isset($filters['ruleNumber'])) {
    $content->where('violation.rule_number', $filters['ruleNumber']);
}

if (isset($filters['unprocessed'])) {
    $content->where('violation.status', 'pending');
}

Upvotes: 2

Related Questions