Wednesday, January 19, 2022

[FIXED] How to check if table is already joined in Laravel Query Builder

Issue

I created a query. I want to join my table with students table:

$query->leftJoin('students', 'learners.student_id', '=', 'students.id');

But I don't know my table joined before or not. How should I do that?


Solution

I found this solution:

function joined($query, $table) {
    $joins = $query->getQuery()->joins;
    if($joins == null) {
        return false;
    }
    foreach ($joins as $join) {
        if ($join->table == $table) {
            return true;
        }
    }
    return false;
}

if ( joined($query, 'students') ) {
    $query->leftJoin('students', 'learners.student_id', '=', 'students.id');
}


Answered By - Roham Rafii

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.