kitten
1 month ago
334
20
Eloquent

Retrieve posts from categories except one

Posted 1 month ago by kitten

Hello!

I'm at my wits end all I have left is pulling my hair :(

My setup is as following: I have Posts & Categories as a many to many relationship

What I need: Select a given number of posts from all categories but one (let's call it Private).

I've tried everything and nothing works and it drives me crazy!!!

One possible solution would be to select all posts and then loop over the collection and exclude the posts found in the Private category but I don;t want to do that since I have a site where I'm collecting data from various sources and every hour I get like 1k+ posts so this is not acceptable so I want to do it in one query yet the solution eludes me :(

This is an example of "not working":

$query = Post::with(['categories' => function($q){
            if ( defined( 'CATEGORY_PRIVATE' ) ) {
                if ( $privateCat = getCategoryPrivate()) {
                    $q->where( 'categories.id', '!=', $privateCat->id );
                }
            }
            return $q;
        }])->where( 'post_status_id', $postStatusID )
            ->where( 'post_type_id', $postTypeID )
            ->whereDate( 'created_at', '>', Carbon::now()->subMonth() )
            ->limit( $number )
            ->inRandomOrder()
            ->get();

Can anyone help, please?

TIA

Please sign in or create an account to participate in this conversation.