Question

Pretty standard setup:

table "Posts", table "Categories" pivot "posts_categories"

/************** CATEGORY MODEL *********/
class Category extends Eloquent
{
 /** standard code**/

public function posts()
{
    return $this->belongsToMany('Post','posts_categories');
}

}

/************* POSTS MODEL ************/
class Post extends Eloquent
{
/** the usual **/
public function categories()
{
    return $this->belongsToMany('Category', 'posts_categories');
}

pivot table with proper foreign keys setup.

I cannot seem to figure how to get ALL POSTS without any categories (or for that matter get categories without any posts, like empty categories)

I would like to do this in eloquent, but in sql it'd be something like:

SELECT *, 
       (SELECT COUNT(id) cnt 
        FROM posts_categories pc 
        WHERE pc.post_id = p.id)  AS cnt   
FROM posts p 
HAVING cnt = 0;
Was it helpful?

Solution

You can use this to get all Posts that have no Category:

$posts = Post::has('categories', '=', 0)->get();
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top