[英]laravel get data when give id not match with join table id
这是我的类别表数据
ID |
---|
1 |
2 |
6 |
7 |
在我的帖子中,我加入了这个category table
这是我的帖子表示例数据
这是我的索引 SQL 查询(当 categy_id 与 category.id 匹配时)然后只有它的 fetch
$post = DB::table('posts)->join('category','posts.category_id','categories.id')-.paginate(10);
由于某种原因,可以删除所选类别,因此我尝试获取已删除类别的帖子数据
这是我的查询
$cpost = DB::table('posts')->join('categories','posts.category_id', '!=' ,'categories.id')->select('post.*')->paginate(5);
但上面根据可用的类别数据查询重复的帖子数据
我想要所有类别 id 的帖子数据与类别表 id 中的不匹配我怎么能得到它?
你为什么要加入这个? 您已经将类别 ID 存储在您的帖子表中。
$cpost = DB::table('posts')->where('category_id','!=', $category_id)->paginate(5);
去尝试一下:
$cpost = DB::table('posts')
->join('categories','posts.category_id', '=' ,'categories.id')
->select('post.*', 'categories.*')
->whereNotIn('posts.category_id', DB::raw('select id from categories'))
->paginate(5);
尝试这个。 键是leftJoin
而不是默认的innerJoin
( join
)。
// posts without assigned or existing category
$posts = \DB::table('posts')
->leftJoin('category','posts.category_id','categories.id')
->whereNull('categories.id')
->paginate(10);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.