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?
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?
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');
}
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);
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');
}
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;
}
In case you use table aliases:
$is_joined = collect($query->joins)->some(function($join) {
return strpos($join->table, 'table_name') !== false;
});
© 2022 - 2024 — McMap. All rights reserved.