Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 317
Roham Rafii Avatar asked Feb 27 '19 09:02

Roham Rafii


People also ask

Which is better eloquent or query builder in Laravel?

Eloquent ORM is best suited working with fewer data in a particular table. On the other side, query builder takes less time to handle numerous data whether in one or more tables faster than Eloquent ORM. In my case, I use ELoquent ORM in an application with tables that will hold less than 17500 entries.

What does get () do in Laravel?

This allows you to add conditions throughout your code until you actually want to fetch them, and then you would call the get() function.

How check query executed or not in Laravel?

To enables query log for my_connection : DB::connection('my_connection')->enableQueryLog(); To get query log for my_connection : print_r( DB::connection('my_connection')->getQueryLog() );


1 Answers

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');
}
like image 166
Roham Rafii Avatar answered Sep 24 '22 01:09

Roham Rafii