【问题标题】:October cms - Eloquent - Issues in creating model query from sql query十月 cms - Eloquent - 从 sql 查询创建模型查询的问题
【发布时间】:2017-03-24 19:14:31
【问题描述】:

我有一个运行正常的 sql 查询

SELECT 
*
FROM
    jml_gkb_eventos
WHERE
id IN (SELECT 
        evento_id
    FROM
        jml_gkb_etiqueta_evento
    WHERE
        etiqueta_id IN (SELECT 
                id
            FROM
                jml_gkb_etiquetas
            WHERE
                etiqueta REGEXP ? ) group by evento_id having count(evento_id) = ?);

但我不知道如何将此 sql 查询转换为 Eloquent 模型查询。我知道我接近解决方案(与此问题here 相关)并尝试了以下代码的一些变体:

        $pesquisa = preg_split('/\s+/', $temp, -1, PREG_SPLIT_NO_EMPTY);
    $cadeiapesquisa = implode('|', $pesquisa);
    $contagem = count($pesquisa);
    if (Session::get('modo') == 0){
        if ( strlen($cadeiapesquisa) > 0 ){
            $this['records'] = Evento::with('etiquetas')->whereHas('etiquetas', function($query) use ($cadeiapesquisa, $contagem){

                $query->where('etiqueta', 'regexp', "$cadeiapesquisa")->groupBy('evento_id')->having('COUNT(evento_id) = '.$contagem);

            })->orderBy('id', 'DESC')->paginate(25);
        } else {
            $this['records'] =Evento::paginate(25);
        }
    }

我让它在内部查询中没有 ->having() 部分的情况下工作,显然没有预期的回报,但没有错误。

我做错了什么?

TIA

JL

[编辑] - 使用上面的代码,我得到以下错误:

【问题讨论】:

    标签: mysql sql laravel eloquent octobercms


    【解决方案1】:

    我发现了问题。它与 'count()' 部分没有被 eloquent 处理。至少在我完成的测试中,对 DB::raw 进行计数可以按预期工作。带有一些调整的整个代码片段是:

            $pesquisa = preg_split('/\s+/', $temp, -1, PREG_SPLIT_NO_EMPTY);
        $cadeiapesquisa = implode('|', $pesquisa);
        $contagem = count($pesquisa);
        if (Session::get('modo') == 0){
            if ( strlen($cadeiapesquisa) > 0 ){
                $this['records'] = Evento::with('etiquetas')->whereHas('etiquetas', function($query) use ($cadeiapesquisa, $contagem){
    
                    $query->where('etiqueta', 'regexp', "$cadeiapesquisa")->groupBy('evento_id')->having(DB::raw("COUNT('etiqueta_id')"), '>=', $contagem );
    
                })->paginate(25);
            } else {
                $this['records'] = Evento::paginate(25);
            }
        }
    

    JL

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-05-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-09-12
      • 1970-01-01
      相关资源
      最近更新 更多