如何检查 table 是否已加入 Laravel 查询生成器

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

我创建了一个查询。我想加入我的 table 和学生 table:

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

但是我不知道我的 table 以前加入过没有。我应该怎么做?

我找到了这个解决方案:

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');
}

你应该试试这个:

这里 $clients->joins(它是一个 JoinClause 对象的数组)并查看 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;
}

另一个解决方案是:

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

或更短的方式:

Collection::make($query->getQuery()->joins)->pluck('table')->contains($table);

如果您使用 table 别名:

$is_joined = collect($query->joins)->some(function($join) {
        return strpos($join->table, 'table_name') !== false;
    });