Laravel 5查询构建器的原始查询

时间:2016-12-27 06:02:38

标签: php laravel-5 query-builder

我有下面的原始mysql查询,我想要做的是将此更改为查询生成器。需要帮助。

SET @groupIds = '11,14';
SET @eventIds = '13,5';
SET @friendIds = '1000022';
SET @userFollowings = '1000001';


$query = "SELECT sn_posts.*
FROM sn_posts
WHERE 
sn_posts.deleted_at is null AND 
(
    sn_posts.user_id = '1000042' OR (
        (
            IF(@groupIds is not null AND @groupIds <> '',FIND_IN_SET(sn_posts.postable_id,@groupIds),0)
            OR IF(@eventIds is not null AND @eventIds <> '',FIND_IN_SET(sn_posts.postable_id,@eventIds),0)
            OR IF(sn_posts.privacy_level = 0, (
                IF(@friendIds is not null AND @friendIds <> '', FIND_IN_SET(sn_posts.`user_id`,@friendIds),0)
                OR IF(@userFollowings is not null AND @userFollowings <> '',FIND_IN_SET(sn_posts.`user_id`,@userFollowings),0)
                ), 
                IF(@friendIds is not null AND @friendIds <> '', FIND_IN_SET(sn_posts.user_id,@friendIds),0)
            )
        )
        AND IF(sn_posts.`parent_id` IS NOT NULL,(
            SELECT parent.id FROM sn_posts AS parent
            WHERE parent.id = sn_posts.`parent_id` AND IF(parent.privacy_level = 0,1,IF(@friendIds is not null AND @friendIds <> '', FIND_IN_SET(parent.`user_id`,@friendIds),0))
            ),1)
    )
)

ORDER BY sn_posts.created_at desc
LIMIT 21,10";
$result = DB::raw(DB::select($query));

我有php变量而不是那些mysql变量。 由于需要将结果作为集合,我需要一种方法将结果作为集合。 我尝试过:

$result = Post::where('deleted_at', null)
        ->where(function($query) use($authUserID,$friendIds,$userFollowings,$groupIds,$eventIds) {
            $query->where('user_id', $authUserID);
                orWhere(function($query) use($friendIds,$userFollowings,$groupIds,$eventIds) {
                    $query->whereIn('postable_id', $groupIds)
                        ->orWhereIn('postable_id', $eventIds)
                        ->orWhere(function($query) use ($friendIds, $userFollowings) {
                            if ($query->where('privacy_level', 0)) {
                                $query->whereIn('user_id', $friendIds)
                                    ->orWhereIn('user_id', $userFollowings);
                            } else {
                                $query->whereIn('user_id', $friendIds);
                            }
                        });
                })->where(function($query) use($friendIds){
                    ***if ($query->whereNotNull('parent_id')) {
                        DB::raw('select parent.id from sn_posts as parent where parent.id = '.$query->parent_id.' 
                        and if(parent.privacy_level = 0,1, 
                        if('.$friendIds.' is not null and '.$friendIds.' <> "", FIND_IN_SET(parent.user_id, '.$friendIds.'), 0))
                    }***
                });
        });

主要问题是检查当前共享帖子的父帖子(星星块之间)的访问级别。这意味着我想检查当前帖子是否是共享帖子,然后检查父母是否是公开帖子,或者是我朋友的帖子,然后获取该共享帖子,否则逃避。

0 个答案:

没有答案