【问题标题】:laravel get data when give id not match with join table idlaravel 在给定 id 与连接表 id 不匹配时获取数据
【发布时间】:2021-03-09 13:36:45
【问题描述】:

这是我的类别表数据

id
1
2
6
7

在我的帖子中,我加入了这个category table

这是我的帖子表示例数据

  1. ID = 1,
  2. name = '你好'
  3. 类别 id = 4(我加入类别表,但选择的类别是 已删除)

这是我的索引 SQL 查询(当 categy_id 与 category.id 匹配时)然后只有它的获取

$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 中的不匹配我怎么能得到它?

【问题讨论】:

    标签: php mysql laravel


    【解决方案1】:

    试试这个。键是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);
    

    【讨论】:

      【解决方案2】:

      你为什么要加入这个?您已经将类别 ID 存储在您的帖子表中。

      $cpost = DB::table('posts')->where('category_id','!=', $category_id)->paginate(5);
      

      【讨论】:

      • 仍然相同 ([1,2,6,7]) 与 4 不匹配所以记录重复 4 次
      【解决方案3】:

      试试吧:

      $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);
      

      【讨论】:

      • 这一行出现错误 >whereNotIn('categories.id', DB::raw('select id from categories'))
      • ->whereNotIn('posts.category_id', DB::raw('select id from categories'))
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-10-20
      • 1970-01-01
      • 2016-05-15
      • 2015-01-05
      • 1970-01-01
      相关资源
      最近更新 更多