How to check if table is already joined in Laravel Query Builder
Asked Answered
P

4

9

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?

Press answered 27/2, 2019 at 9:52 Comment(0)
P
11

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 not already joined, then join
if ( !joined($query, 'students') ) {
    $query->leftJoin('students', 'learners.student_id', '=', 'students.id');
}
Press answered 27/2, 2019 at 9:52 Comment(0)
P
13

Another solution is:

function isJoined($query, $table){
    $joins = collect($query->getQuery()->joins);
    return $joins->pluck('table')->contains($table);
}

or shorter way:

Collection::make($query->getQuery()->joins)->pluck('table')->contains($table);
Press answered 27/2, 2019 at 9:55 Comment(0)
P
11

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 not already joined, then join
if ( !joined($query, 'students') ) {
    $query->leftJoin('students', 'learners.student_id', '=', 'students.id');
}
Press answered 27/2, 2019 at 9:52 Comment(0)
C
2

You should try this:

Here $clients->joins (It's an array of JoinClause objects) and look at JoinClause->table.

function hasJoin(\Illuminate\Database\Query\Builder $Builder, $table) //$table as table name
{
    foreach($Builder->joins as $JoinClause)
    {
        if($JoinClause->table == $table)
        {
            return true;
        }
    }
    return false;
}
Chorister answered 27/2, 2019 at 9:55 Comment(0)
M
0

In case you use table aliases:

$is_joined = collect($query->joins)->some(function($join) {
        return strpos($join->table, 'table_name') !== false;
    });
Mares answered 22/9, 2020 at 18:12 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.