[英]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.