如何从原始查询转换为Eloquent?

时间:2015-09-17 03:36:20

标签: laravel

我有这样的查询语法:

return \DB::select(\DB::raw("select * from news where who_see='6' or (news.id_user IN (select id_user from koneksi_user where to_id_user=$user->id_user and confirmed='0') OR news.id_user IN(select to_id_user from koneksi_user where id_user=$user->id_user and confirmed='0'))) order by created_at desc"));

但是当我在Eloquent中这样使用时:

return \DB::table('news')
            ->where('who_see','6')
            ->WhereIn('news.id_user', function($query)
                {
                    $query->select('id_user')
                    ->from('koneksi_user')
                    ->whereRaw('to_id_user=$user->id_user');
                })
            ->WhereIn('news.id_user', function($query2)
                {
                    $query2->select('id_user')
                    ->from('koneksi_user')
                    ->whereRaw('id_user=$user->id_user');
                })
            ->get();

我收到的错误是这样的:

SQLSTATE[42601]: Syntax error: 7 ERROR: 'sintaks error' pada atau didekat « $ » LINE 1: ...ct "id_user" from "koneksi_user" where to_id_user=$user->id_... ^ (SQL: select * from "news" where "who_see" = 6 and "news"."id_user" in (select "id_user" from "koneksi_user" where to_id_user=$user->id_user) and "news"."id_user" in (select "id_user" from "koneksi_user" where id_user=$user->id_user))

1 个答案:

答案 0 :(得分:0)

乍一看,这是因为你试图在单引号内使用$ user。那不行。正如您在错误消息中看到的那样,$ user按字面意思放在查询中。

最好使用查询参数,例如

->whereRaw("to_id_user=?", array($user->id_user));