mysql - Laravel Eloquent : Many-to-Many Select items without children (using pivot)

标签 mysql laravel eloquent

非常标准的设置:

表“帖子”, 表“类别” 透视“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/

相关文章:

mysql - 在 MySQL 中插入唯一行的最便宜的方法?

php - Laravel Eloquent 4 表关系

php - 从模型中获取所有在数据透视表 Laravel 5 中没有条目的记录

php - Laravel Eloquent Pluck 不丢 key

php - Laravel apiResource 按 id 以外的字段获取记录

带条件的 laravel 数据透视表

MySQL:多主键和自增

php - 将票务系统添加到现有的 PHP/MySQL 应用程序?

mysql - MariaDB/MySQL 查询区分大小写吗?

javascript - PHP json_encode 输出带引号的数字