I am learning laravel. I want to write following query in laravel using eloquent:
select b.branch_name, w.branch_work_name from branches AS b, branch_work_metadata AS w, branch_work_lookup AS bw where b.branch_id = bw.branch_id AND w.branch_work_id = bw.branch_work_id
Above query works perfectly in phpmysql
I have Models for each table as follows:
Table: branches --- Model: Branch
Table: branch_work_metadata --- Model: BranchWorkMetadata
Table: branch_work_lookup --- Model: BranchWorkLookup
When I tried to write above query in laravel it gives me error
$branch = DB::table('branches as b', 'branch_work_metadata as w', 'branch_work_lookup as bw')
->select('b.branch_name','w.branch_work_name')
->join('b.branch_id','=','bw.branch_id')
->join('w.branch_work_id','=','bw.branch_work_id')
->get();
Above gives me error
Illuminate\Database\QueryException
SQLSTATE[42S02]: Base table or view not found: 1146 Table 'b.branch_id' doesn't exist (SQL: select `b`.`branch_name`, `w`.`branch_work_name` from `branches` as `b` inner join `b`.`branch_id` on `=` = `bw`.`branch_id` inner join `w`.`branch_work_id` on `=` = `bw`.`branch_work_id`)
Also tried following:
$branch = BranchWorkLookup::Join('branches.branch_id','=','branch_work_lookup.branch_id')
->Join('branch_work_metadata.branch_work_id','=','branch_work_lookup.branch_work_id')
->select(
'branches.branch_name',
'branch_work_name'
)
->get();
giving error
Illuminate\Database\QueryException
SQLSTATE[42S02]: Base table or view not found: 1146 Table 'branches.branch_id' doesn't exist (SQL: select `branches`.`branch_name`, `branch_work_name` from `branch_work_lookup` inner join `branches`.`branch_id` on `=` = `branch_work_lookup`.`branch_id` inner join `branch_work_metadata`.`branch_work_id` on `=` = `branch_work_lookup`.`branch_work_id`)
Whats going wrong? Not able to find solution. Please help. Thanks in advance.
You are trying to mix the old school join syntax with the modern version used by Laravel's query builder, which is also the version you should be using. Try this instead:
$branch = DB::table('branches as b')
->select('b.branch_name', 'w.branch_work_name')
->join('branch_work_lookup as bw', 'b.branch_id', '=', 'bw.branch_id')
->join('branch_work_metadata as w', 'w.branch_work_id', '=', 'bw.branch_work_id')
->get();
To be clear, this is the raw MySQL query you should be using:
SELECT
b.branch_name,
w.branch_work_name
FROM branches AS b
INNER JOIN branch_work_lookup bw
ON b.branch_id = bw.branch_id
INNER JOIN branch_work_metadata AS w
ON w.branch_work_id = bw.branch_work_id;
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.