非常标准的设置:
表“帖子”, 表“类别” 透视“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 = Post::has('categories', '=', 0)->get();
关于mysql - Laravel Eloquent : Many-to-Many Select items without children (using pivot),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25028078/