简体   繁体   中英

How to select sub-query with left join inside using eloquent?

I'm very new to Laravel, how can I make this query in Laravel using Eloquent model:

SELECT
(
  SELECT departments.deptname FROM school.counts
  LEFT JOIN reference.departments
  ON counts.departmentcode = department.departmentcode
  WHERE counts.countid = a.countsid
) AS departmentDesc
FROM school.subjecthdr a
LEFT JOIN school.subjectdtls b
ON a.subjectid = b.subjectid;

I don't wish to use raw queries, is there any way? I still appreciate raw query suggestions if there's any.

I think you still need some raw queries.

$dept_desc = \DB::table('school.counts')
->leftjoin('reference.departments', 'counts.departmentcode', '=', 'departments.departmentcode')
->whereRaw('counts.countid = a.countsid')
->selectRaw('departments.deptname');


\DB::table('school.subjecthdr AS a')
->leftjoin('subjectdtls AS b', 'a.subjectid', '=', 'b.subjectid')
->selectRaw('(' . $dept_desc->toSql() . ') AS departmentDesc')
->get();

PS: I think you leftjoin subjectdtls b but it seems you don't need it.

And you are using not only one database, if you want to use Eloquent\Builder , you need to do something like this: How to use multiple databases in Laravel

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM