有没有办法将这个查询翻译成Laravel雄辩的格式?
SELECT TEMP.A, COUNT(*) AS Total FROM
(SELECT A FROM TABLE WHERE B='something' GROUP BY C)
AS TEMP GROUP BY TEMP.A
我在这里要做的是根据特定where子句中C的不同记录得到A的计数。
subselect语句也是由用户输入在过滤器上构建的雄辩对象,用于获取C out的不同记录。 我尝试这样做,假设subselect eloquent对象是$ query
$query2->DB::connection()->table(function($_query) use ($query){
$_query = $query;
$_query->addSelect('A')->where('B','=','something')->groupBy('C')->get();
})->addSelect('A')->addSelect(DB::raw('COUNT(*) as Total'))->groupBy('A')->get();
但它似乎没有起作用,有人建议使用DB :: raw in - > table(),但问题是subselect语句实际上也是一个动态构建的eloquent语句。
非常感谢您提前提供的帮助
答案 0 :(得分:3)
子查询与Eloquent不能很好地协作。你只是给自己头疼,敢于尝试。我建议使用DB:select(),然后在模型中添加hydrate(),并使用它将其转换为Eloquent。这就是我处理复杂查询的方式:
包含查询的文件:
<?php
$query = "SELECT TEMP.A, COUNT(*) AS Total FROM (SELECT A FROM TABLE WHERE B='?' GROUP BY C) AS TEMP GROUP BY TEMP.A";
$thing_query = DB::select($query, ['something']);
$thing = Thing::hydrate($thing_query);
// hydrate converted it into Eloquent so we can use things like first()
return $thing->first()->total;
模型/ Thing.php
<?php
class Thing extends Eloquent {
/**
* Hydrate method
*
* @param array $data
* @return Illuminate\Database\Eloquent\Collection
*/
static public function hydrate(array $data, $connection = NULL)
{
// get calling class so we can hydrate using that type
$klass = get_called_class();
// psuedo hydrate
$collection = new Illuminate\Database\Eloquent\Collection();
foreach ($data as $raw_obj)
{
$model = new $klass;
$model = $model->newFromBuilder($raw_obj);
if (!is_null($connection))
$model = $model->setConnection($connection);
$collection->add($model);
}
return $collection;
}
}