php - SQL 存在于 Laravel 5 查询生成器中

标签 php postgresql laravel

早上好

我花了很多时间尝试将此查询(返回一个 stdClass 数组)转换为查询构建器,以便我可以将对象作为 Eloquent 模型取回。

这是未翻译查询的样子:

$anketa = DB::select( DB::raw("SELECT * 
                                         FROM v_anketa a 
                                        WHERE not exists (select 1 from user_poeni where anketa_id=a.id and user_id = :lv_id_user)
                                        Order by redni_broj limit 1"
                                     ), array(   'lv_id_user' => $id_user,
                ));

我已经试过了,但是它在子查询的内部 from 附近给出了一个语法错误:

$anketa = V_anketa::selectRaw("WHERE not exists (select 1 from user_poeni where anketa_id=a.id and user_id = :lv_id_user)", array('lv_id_user' => $id_user,)
                            )->orderBy('redni_broj')->take(1)->first();

问题是它存在并且其中有一个子查询。我找不到关于这种特殊情况的任何信息。

假设每个表都有一个合适的 Eloquent 模型。 V_anketa 是一种观点。数据库是 postgresql。

最佳答案

就查询而言,我相信这应该有效:

$anketa = V_anketa::whereNotExists(function ($query) use ($id_user) {
                $query->select(DB::raw(1))
                      ->from('user_poeni')
                      ->where('anketa.id', '=', 'a.id')
                      ->where('user_id', '=', $id_user);
            })
           ->orderBy('redni_broj')
           ->first();

但我不清楚“假设每个表都有一个 Eloquent 模型”和“V_anketa”是一个 View 是什么意思...

关于php - SQL 存在于 Laravel 5 查询生成器中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33666479/

相关文章:

php - Eloquent 不会检索我作为 csv 导入的 mysql 表,但查询生成器会检索

laravel - 找不到[layouts.app]。 Laravel框架5.4.36

尝试在 aws ec2 ubuntu 上运行 npm run dev 时,Laravel Vue 卡住了

c# - 无法将 PostgreSQL 中的文件作为大对象存储然后读取

python - SQL/ python : Transform data from csv and into table with different schema with condition

postgresql - plpgsql:将变量串联到 FROM 子句中

Laravel:使用相关模型的范围来过滤结果

php - 显示数据库中的图像并将其链接到另一个页面

php - 按子键日期对多维数组进行排序?

php - 如何从多个mysql表中获取数据并生成一个JSON输出