相当标准的设置:

表"帖子", 表"类别" 枢轴"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');
}

具有正确外键设置的数据透视表。

我似乎无法弄清楚如何在没有任何类别的情况下获得所有帖子(或者在没有任何帖子的情况下获得类别,如空类别)

我想在eloquent中做到这一点,但在sql中它会是这样的:

SELECT *, 
       (SELECT COUNT(id) cnt 
        FROM posts_categories pc 
        WHERE pc.post_id = p.id)  AS cnt   
FROM posts p 
HAVING cnt = 0;
有帮助吗?

解决方案

你可以用这个来获得所有 Posts 那没有 Category:

$posts = Post::has('categories', '=', 0)->get();
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top