简体   繁体   中英

MySQL query to Laravel Eloquent

I have the following MySQL query:

SELECT 
    *
FROM
    news_posts
WHERE
    user_id = ?
        AND id NOT IN (SELECT 
            post_id
        FROM
            user_read
        WHERE
            user_id = ?)

I want to make it more "eloquent". I've tried the following, but its (obviously) not working:

NewsPost::where('user_id', Auth::id())
    ->whereNotIn(function ($query) {
        $query->DB::table('user_read')
            ->select('post_id')
            ->where('user_id', Auth::id());
    })->get();

I'm assuming the 'where' method is executing a simple SQL query on 'new_posts' table. Can you try to rewrite this query and let mysql do the filtering for new posts? (search for LEFT OUTER JOIN on mysql)

SELECT *
FROM news_posts a
JOIN user_read b
ON a.id = b.post_id
WHERE a.user_id = ?
AND b.post_id IS NULL;

Thanks for all the replies! Got it working with the following tweaks:

 NewsPost::where('user_id', Auth::id())
                ->whereNotIn('id', function ($query) {
                $query->select('post_id')
                ->from('user_read')
                ->where('user_id', Auth::id());
            })
            ->get();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM