gpt4 book ai didi

Laravel 从派生表中选择

转载 作者:行者123 更新时间:2023-12-02 10:25:10 28 4
gpt4 key购买 nike

有没有办法将此查询转换为 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 的计数。

子选择语句也是一个 Eloquent 对象,它是通过用户在过滤器上的输入构建的,以获取 C 的不同记录。我尝试这样做,假设子选择 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(),然后将 Hydro() 添加到您的模型中,并使用它将其转换为 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/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com