Laravel多表原始查询到Eloquent

时间:2016-02-24 12:06:36

标签: php laravel

SELECT * FROM
  (
    SELECT t1.personId
    FROM
      (
        SELECT * FROM `skills`
        WHERE `title` = 'SaaS'
        GROUP BY `personId`
      ) t1
      INNER JOIN
      (
        SELECT * FROM `languages`
        WHERE `title` = 'English'
        GROUP BY `personId`
      ) t2
      INNER JOIN
      (
        SELECT * FROM `education`
        WHERE `title` = 'Louisiana State University'
        GROUP BY `personId`
      ) t3 ON t1.personId = t2.personId AND t2.personId = t3.personId
  ) tr
  LEFT JOIN `people` ON people.id = tr.personId

如何将此Sql字符串转换为Laravel Eloquert或DB查询?

2 个答案:

答案 0 :(得分:0)

不测试,但尝试一下,看看它是怎么回事

DB::table('tr')->select("tr.*")
 ->from("(
    SELECT t1.personId
    FROM
      (
        SELECT * FROM `skills`
        WHERE `title` = 'SaaS'
        GROUP BY `personId`
      ) t1
      INNER JOIN
      (
        SELECT * FROM `languages`
        WHERE `title` = 'English'
        GROUP BY `personId`
      ) t2
      INNER JOIN
      (
        SELECT * FROM `education`
        WHERE `title` = 'Louisiana State University'
        GROUP BY `personId`
      ) t3 ON t1.personId = t2.personId AND t2.personId = t3.personId
  ) as tr")
->leftJoin('people','people.id','=','tr.personId')
->get();

答案 1 :(得分:0)

我实现了类似这样的工作......

                $this->SalesGroup_model->select('sales_group.id','sales_group.name','sales_group.from_weight','sales_group.to_weight','sales_group.amount',DB::raw("sum(sales_item.net_weight) as total_sales"))
                   ->leftJoin('sales_item',function($join){
                       $join->on('sales_item.net_weight','>=','sales_group.from_weight');
                       $join->on('sales_item.deleted','=',DB::raw('"0"'));
                   })
                   ->groupBy('sales_group.id');
                $object = DB::table(DB::raw("({$sub->toSql()}) as one"))
               ->mergeBindings($sub->getQuery())
               ->join(DB::raw('(SELECT sales_group.id,
                   count(mysales.employee_id) AS "total_person"
                       FROM `sales_group`
                       LEFT JOIN
                           (SELECT sales_item.net_weight,
                           sales_challan.employee_id
                           FROM sales_item
                           INNER JOIN sales_challan ON sales_challan.id=sales_item.challans_id
                           GROUP BY sales_item.challans_id,
                           sales_challan.employee_id) mysales ON mysales.net_weight>=sales_group.from_weight
                           AND mysales.net_weight<=sales_group.to_weight
                           GROUP BY sales_group.id) two'),function($join){
                           $join->on('two.id','=','one.id');
               })->get();