vendredi 20 mai 2016

Laravel Join and subquery

Is there anything wrong in the following eloquent query?i getting error message

SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'LIMTI 1) AS comment_1 on users_posts.id = comment'

        $up = UserPosts::select('users_posts.id AS id');

        //A lot of other join and addSelect here...

        $up->addSelect(\DB::raw("
            comment_1.content AS comment_1_content, comment_1.user_id AS comment_1_user_id, comment_1.avatar AS comment_1_avatar, comment_1.gender AS comment_1_gender, comment_1.username AS comment_1_username
        "));

        $up->join(\DB::raw('
                (SELECT users_posts_comments.content AS content, users_posts_comments.user_id AS user_id, users.avatar AS avatar, users.gender AS gender, CONCAT(users.first_name, " ", users.last_name) AS username
                FROM users_posts_comments LEFT JOIN users ON users_posts_comments.user_id = users.id WHERE users_posts_comments.user_post_id = users_posts.id ORDER BY users_posts_comments.id DESC LIMTI 1)
                AS comment_1
            '), function ($join) {
                $join->on(\DB::raw('users_posts.id'), '=', \DB::raw('comment_1.user_post_id'));
            }
        );

        $up->leftJoin('users', 'users.id', '=', 'users_posts.user_id')
        ->whereIn('users_posts.user_id', $myFriends);

        return $up->orderBy('users_posts.created_at', 'DESC');

there is users, users_posts, users_posts_comments table and users_posts_comments.user_post_id foreign users_posts id which i want to select users_posts and join the latest 2 comment from users_posts_comments table, i think to use the join users_posts_comments AS comment_1 and repeat the comment_1 query to be comment_2 and ORDER BY id DESC and skip 1, how can i do this?

a query retrieve multiples users_posts rows and each users_posts join comment_1 and comment_2

i cannot use the model hasMany because this select post query has join a lot of others table already which i didnt paste here



from Newest questions tagged laravel-5 - Stack Overflow http://ift.tt/1qy1Byb
via IFTTT

Aucun commentaire:

Enregistrer un commentaire