SQL到Laravel查询生成器

时间:2017-06-27 15:36:36

标签: sql laravel laravel-5

我很难将原始SQL转换为使用Laravel Query Builder构建的SQL字符串。

Here你可以阅读我的问题,看看我得到的答案。我收到的答案需要使用模型(Time)而不是\DB::

从原始SQL转换为使用Laravel查询生成器构建的SQL字符串

我使用原始SQL。其中 4298584 $id变量。不幸的是,它返回一个这样的数组:

// php
$times = \DB::select( \DB::raw(
    "SELECT t.* FROM times t
        JOIN (SELECT ath_id, stroke_id, MIN(time)
              AS time
              FROM dbo.times
              GROUP BY ath_id, stroke_id
        ) b
        ON t.ath_id = b.ath_id
        AND t.stroke_id = b.stroke_id
        AND t.time = b.time
        WHERE t.ath_id = 4298584
        ORDER BY t.stroke_id ASC, t.date DESC"
) );

// returns:
array:40 [▼
  0 => {#217 ▼
    +"id": 72073658
    +"ath_id": 4298584
    +"stroke_id": 1
    +"time": 1104
    +"date": "28 Jun 2015"
  }
]

而不是包含所有模型的数组:

// php:
$times = Time::where('ath_id', '=', $id)
             ->groupby('stroke_id')
             ->get();

// returns:
Collection {#219 ▼
  #items: array:39 [▼
    0 => Time {#220 ▼
      #fillable: array:7 [▶]
      #attributes: array:9 [▼
        "id" => 72073658
        "ath_id" => 4298584
        "stroke_id" => 1
        "time" => 1104
        "date" => "28 Jun 2015"
      ]
      #original: array:9 [▼
        "id" => 72073658
        "ath_id" => 4298584
        "stroke_id" => 1
        "time" => 1104
        "date" => "28 Jun 2015"
      ]
    }
  ]
}

我的times表的型号名称为 Time 。我希望将数据库中的结果放在名为$times的变量中。

我需要使用Time::class

转换以下SQL
SELECT t.* FROM times t
JOIN (SELECT ath_id, stroke_id, MIN(time) AS time FROM swimrankings.times 
      GROUP BY ath_id, stroke_id) b
  ON t.ath_id = b.ath_id AND t.stroke_id = b.stroke_id AND t.time = b.time
WHERE t.ath_id = 4298584
ORDER BY t.stroke_id ASC, t.date DESC"

解决方案失败:

我认为这是解决方案。我使用Laravel Query Builder重新创建了SQL查询。但是返回的Collection对象中有一个名为Items的空数组。通常是模型所在的位置。

$times = Time::select('*')
             ->join(\DB::raw('(SELECT ath_id, stroke_id, MIN(time) AS time FROM times GROUP BY ath_id, stroke_id) b'), function($join) {
                 $join->on('times.ath_id', '=', 'b.ath_id')
                      ->where('times.stroke_id', '=', 'b.stroke_id')
                      ->where('times.time', '=', 'b.time');
             })
             ->where('times.ath_id', '=', $id)
             ->orderBy('times.stroke_id', 'ASC')
             ->orderBy('times.date', 'DESC')
             ->get();

// returns the following query:
// "SELECT * FROM `times` INNER JOIN (SELECT `ath_id`, `stroke_id`, MIN(time) AS time FROM times GROUP BY ath_id, stroke_id) b ON `times`.`ath_id` = `b`.`ath_id` AND `times`.`stroke_id` = b.stroke_id AND `times`.`time` = b.time WHERE `times`.`ath_id` = 4298584 ORDER BY `times`.`stroke_id` ASC, `times`.`date` DESC"
// but does not work

0 个答案:

没有答案