laravellaravel-query-builder

Laravel Query Builder: joining tables by from / where


Joining multiple tables in Query Builder is so simple:

DB::table('projects')
->select('tasks.*')
->join('tasks', 'tasks.project_id', 'projects.id')

But for now customer asks me to avoid join usage:

SELECT tasks.*
FROM projects, tasks
WHERE tasks.project_id = projects.id

How to do it?

Usage of Builder's method from is bad idea:

P.S. Please do not waste time to describe how Eloquent works - I need to know how to do it just with Laravel Query Builder. If it's possible with LQB, of course


Solution

  • while I would say to use the Join syntax, since it's much more clear what you are doing and any performance difference in negligible if none, if you really want to build your query you can pass to any query method, a "raw" instance to have it build your query as is

    DB::table(DB::raw('projects, tasks'))
        ->select('tasks.*')
        ->whereColumn('tasks.project_id', 'projects.id')
        ->dd();
    

    results in: select `tasks`.* from projects, tasks where `tasks`.`project_id` = `projects`.`id`