Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

king_eke's avatar

Convert Eloquent Query to SQL

Hello guys, happy new year.

Please can someone help me convert this eloquent query to a raw SQL query where I can use in phpMyAdmin to get the same result.

The database structure is

An employee hasOne profile, the profile hasOne introductionTranslation which translates the introduction text to different languages being spanish and french and just stores the id of the translation on the profile table. Same goes for work experience and education.

the query is

$employee = Employee::with(
        [
            'profile',
            'profile.introduction_translations',
            'profile.work_experience_translations',
            'profile.education_translations'
        ]
    )->first();

this is the sample response

array:10 [▼
  "name" => "Chinonso Eke"
  "birth_date" => "1996-05-13"
  "ssn" => "2231312321321321"
  "current_employee" => 1
  "email" => "[email protected]"
  "phone" => "07063944465"
  "address" => "Lagos, Nigeria"
  "created_at" => "2020-01-07 18:38:10"
  "updated_at" => "2020-01-07 18:38:10"
  "profile" => array:8 [▼
    "introduction" => """
      A paragraph is a group of words put together to form a group that is usually longer than a sentence. Paragraphs are often made up of several sentences. There ar ▶
      
                  In most organized forms of writing, such as essays, paragraphs contain a topic sentence . This topic sentence of the paragraph tells the reader what ▶
                  
                  Paragraphs may signal when the writer changes topics. Each paragraph may have a number of sentences, depending on the topic.
      """
    "work_experience" => """
      Work experience called internship in North American English, is any experience that a person gains while working in a specific field or occupation, but the expr ▶
      
                  Though the placements are usually unpaid, travel and food expenses are sometimes covered, and at the end of the appointment, a character reference i ▶
      """
    "education" => "Education is the process of facilitating learning, or the acquisition of knowledge, skills, values, beliefs, and habits. Educational methods include teaching, t ▶"
    "created_at" => "2020-01-07 18:38:10"
    "updated_at" => "2020-01-07 18:38:10"
    "introduction_translations" => array:4 [▼
      "text_ES" => """
        Un párrafo es un grupo de palabras juntas para formar un grupo que generalmente es más largo que una oración. Los párrafos a menudo se componen de varias oracio ▶
        
                    En la mayoría de las formas organizadas de escritura, como los ensayos, los párrafos contienen una oración temática. Esta oración temática del párra ▶
                    
                    Los párrafos pueden indicar cuándo el escritor cambia de tema. Cada párrafo puede tener varias oraciones, según el tema.
        """
      "text_FR" => """
        Un paragraphe est un groupe de mots réunis pour former un groupe qui est généralement plus long qu'une phrase. Les paragraphes sont souvent composés de plusieur ▶
        
                    Dans la plupart des formes d'écriture organisées, comme les essais, les paragraphes contiennent une phrase de sujet. Cette phrase de sujet du paragr ▶
                    
                    Les paragraphes peuvent signaler quand l'auteur change de sujet. Chaque paragraphe peut avoir un certain nombre de phrases, selon le sujet.
        """
      "created_at" => "2020-01-07 18:38:10"
      "updated_at" => "2020-01-07 18:38:10"
    ]
    "work_experience_translations" => array:4 [▼
      "text_ES" => """
        La experiencia laboral llamada pasantía en inglés norteamericano es cualquier experiencia que una persona adquiere mientras trabaja en un campo u ocupación espe ▶
        
                    Aunque las ubicaciones generalmente no son remuneradas, los gastos de viaje y comida a veces están cubiertos, y al final de la cita, generalmente se ▶
        """
      "text_FR" => """
        Une expérience de travail appelée stage en anglais nord-américain, est toute expérience qu'une personne acquiert en travaillant dans un domaine ou une professio ▶
        
                    Bien que les placements soient généralement non rémunérés, les frais de voyage et de nourriture sont parfois couverts et, à la fin du rendez-vous, u ▶
        """
      "created_at" => "2020-01-07 18:38:10"
      "updated_at" => "2020-01-07 18:38:10"
    ]
    "education_translations" => array:4 [▼
      "text_ES" => "La educación es el proceso de facilitar el aprendizaje o la adquisición de conocimientos, habilidades, valores, creencias y hábitos. Los métodos educativos incl ▶"
      "text_FR" => "L'éducation est le processus qui facilite l'apprentissage ou l'acquisition de connaissances, de compétences, de valeurs, de croyances et d'habitudes. Les méthod ▶"
      "created_at" => "2020-01-07 18:38:10"
      "updated_at" => "2020-01-07 18:38:10"
    ]
  ]
]

0 likes
13 replies
Sti3bas's avatar

@king_eke just run this and it will dump raw SQL query:

\DB::enableQueryLog();

$employee = Employee::with([
    'profile',
    'profile.introduction_translations',
    'profile.work_experience_translations',
    'profile.education_translations'
])->first();

dd(\DB::getQueryLog());
4 likes
narendrakumar's avatar

@Sti3bas Thanks, it helped my project debugging. TO site Admin: I understand it's 3 year old thread, but I wanted to show my thanks that this post is still helping for the needles like me, that's why commented here. Hope it doesn't hurt your policy of commenting in 3 year old thread as I used to see that in many threads you are asking user to not comment in old thread.

1 like
jlrdw's avatar

You can enable logging:

DB::enableQueryLog();
// query

DB::getQueryLog();

Or at end of query try ->toSql()

2 likes
king_eke's avatar

@sti3bas thank you. the output is this


array:5 [▼
  0 => array:3 [▼
    "query" => "select * from `employees` limit 1"
    "bindings" => []
    "time" => 3.57
  ]
  1 => array:3 [▼
    "query" => "select * from `profiles` where `profiles`.`employee_id` in (1)"
    "bindings" => []
    "time" => 0.93
  ]
  2 => array:3 [▼
    "query" => "select * from `translations` where `translations`.`id` in (?)"
    "bindings" => array:1 [▶]
    "time" => 0.61
  ]
  3 => array:3 [▼
    "query" => "select * from `translations` where `translations`.`id` in (?)"
    "bindings" => array:1 [▶]
    "time" => 0.29
  ]
  4 => array:3 [▼
    "query" => "select * from `translations` where `translations`.`id` in (?)"
    "bindings" => array:1 [▶]
    "time" => 0.43
  ]

but i was hoping to see JOINS and UNION and all that in the query, so it would be like one single query to get it all done

king_eke's avatar

@jlrdw thanks for the reply, but it doesn't show a single query like i wanted, i was hoping to see JOINS and UNION and all that in the query, so it would be like one single query to get it all done

jlrdw's avatar

Did you try toSql

$query = your query.........
print_r($query->toSql());
print_r($query->getBindings());
king_eke's avatar

@jlrdw i got

select * from `employees`Array ( )

this is my code

use App\Employee;

Route::get('/', function () {

    \DB::enableQueryLog();

    $employee = Employee::with(
        [
            'profile',
            'profile.introduction_translations',
            'profile.work_experience_translations',
            'profile.education_translations'
        ]
    )->first();

    print_r($employee->toSql());
    print_r($employee->getBindings());

    // dd(DB::getQueryLog());

    // return view('welcome', compact('user'));
});

Sti3bas's avatar

@king_eke seems like the relationships you are trying to load are one-to-many so it's not possible to load them with the JOIN.

king_eke's avatar

@sti3bas no, they'e one to one

the employee model

 public function profile()
    {
        return $this->hasOne('App\Profile');
    }

the profile model


public function employee()
    {
        return $this->belongsTo('App\Employee');
    }

    public function introduction_translations()
    {
        return $this->hasOne('App\Translation', 'id', 'introduction_translation_id');
    }

    public function work_experience_translations()
    {
        return $this->hasOne('App\Translation', 'id', 'work_experience_translation_id');
    }

    public function education_translations()
    {
        return $this->hasOne('App\Translation', 'id', 'education_translation_id');
    }

the translation model

class Translation extends Model
{
    protected $hidden = ['id'];
}

king_eke's avatar
king_eke
OP
Best Answer
Level 1

well, didn't find a way to convert it using laravel, so had to create the sql myself

SELECT * from employees e 
JOIN profiles p on e.id = p.employee_id 
JOIN translations t1 on p.introduction_translation_id = t1.id
JOIN translations t2 on p.work_experience_translation_id = t2.id
JOIN translations t3 on p.education_translation_id = t3.id
where email = "[email protected]"
Pciranda's avatar

Create toRawSql Macro.

class AppServiceProvider extends ServiceProvider
{
    /**
     * Register any application services.
     *
     * @return void
     */
    public function register()
    {
        \Illuminate\Database\Query\Builder::macro('toRawSql', function(){
            return array_reduce($this->getBindings(), function($sql, $binding){
                return preg_replace('/\?/', is_numeric($binding) ? $binding : "'".$binding."'" , $sql, 1);
            }, $this->toSql());
        });

        \Illuminate\Database\Eloquent\Builder::macro('toRawSql', function(){
            return ($this->getQuery()->toRawSql());
        });
    }

Use

Employee::where('name', 'Joe')->toRawSql();

// select * from employees where name = 'joe'

with() will run in separate queries, so you won't see the same query.

Open tinker and run:

DB::listen(function($q){dump($q->sql);});

Employee::with(['profile'])->first();

Exemple:

1 like
ahmtareq25's avatar

I have written this method

    public static function generateQuery($bindings,$query){
			$explodedData = explode('?', $query);
    if (count($bindings) > 0) {
        $finalQuery = '';
        foreach ($explodedData as $key => $queryPart) {

            if (next($explodedData)) {
                $value = $bindings[$key];
                if (is_string($value)) {
                    $finalQuery .= $queryPart . "'" . $value . "'";
                } else {
                    $finalQuery .= $queryPart . $value;
                }
            } else {
                if (isset($bindings[$key])) {
                    $value = $bindings[$key];
                    if (is_string($value)) {
                        $finalQuery .= $queryPart . "'" . $value . "'";
                    } else {
                        $finalQuery .= $queryPart . $value;
                    }
                } else {
                    $finalQuery .= $queryPart;
                }

            }

        }
        $sql = $finalQuery . ';';
    }else{
        $sql = $query;
    }
  
    return $sql;
}

Please or to participate in this conversation.