[英]SQL exists in Laravel 5 query builder
Good morning, 早上好,
I've been trying for quite a lot of time to translate this query(which returns an array of stdClass) into query builder so I could get objects back as Eloquent models. 我已经花了很多时间尝试将此查询(返回一个stdClass数组)转换为查询生成器,以便可以将对象作为Eloquent模型返回。
This is how the query looks like untranslated: 这是查询看起来像未翻译的样子:
$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,
));
I have tried this, but it gives a syntax error near the inner from in the subquery: 我已经尝试过了,但是它在子查询的内部附近给出了语法错误:
$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();
The problem is this exists and a subquery in it. 问题是这存在并且其中有一个子查询。 I couldn't find anything regarding this special case. 关于这种特殊情况,我找不到任何东西。
Assume each table has an appropriate Eloquent model. 假设每个表都有一个合适的口才模型。 V_anketa is a view. V_anketa是一个视图。 The db is postgresql. 该数据库是postgresql。
As far as the query goes I believe this should work: 就查询而言,我相信这应该可行:
$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();
but I'm not clear on what do you mean by "assuming every table has an Eloquent model" and "V_anketa" is a view... 但是我不清楚“假设每个表都有一个Eloquent模型”是什么意思,而“ V_anketa”是一个视图是什么意思...
Assuming the SQL query is correct, this should work: 假设SQL查询正确,则应该可以:
$anketa = DB::select(sprintf('SELECT * FROM v_anketa a WHERE NOT EXISTS (SELECT 1 FROM user_poeni WHERE anketa_id = a.id AND user_id = %s) ORDER BY redni_broj LIMIT 1', $id_user));
If you want to get back an Builder instance you need to specify the table: 如果要取回一个Builder实例,则需要指定表:
$anketa = DB::table('')->select('');
If you however, want to get an Eloquent Model instance, for example to use relations, you need to use Eloquent . 但是,如果要获取Eloquent Model实例(例如,使用关系),则需要使用Eloquent 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.