有没有办法将此查询转换为 Laravel Eloquent 格式?
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 语句也是 eloquent 对象,它由用户在过滤器上的输入构建,以获取 C 的不同记录。
我尝试这样做,假设 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();
但它似乎不起作用,有人建议在->table() 中使用 DB::raw,但问题是 subselect 语句实际上也是一个动态构建的 eloquent 语句。
非常感谢您提前提供帮助
最佳答案
子查询不能很好地与 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;
}
}
关于Laravel 从派生表中选择,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/22312586/