【问题标题】:Laravel. Eloquent query for two tables拉拉维尔。两个表的雄辩查询
【发布时间】:2015-08-24 10:36:47
【问题描述】:


我想编写 laravel 雄辩的查询,它可以从title_count 表中不存在title_id 的titles 表中选择所有标题。这是一个例子。

标题表:

title_id
    1
    2
    3
    4

title_count 表:

title_id 
    3
    4

所以我的查询应该从标题表中选择 id 为 1、2 的标题。老实说,我不知道该怎么做。我正在使用 laravel 5。
希望你能帮助我。提前致谢!

【问题讨论】:

  • 也许你正在寻找集合函数(因为 Eloquent 返回 Collection 对象); laravel.com/api/4.2/Illuminate/Database/Eloquent/… $titles->all()->diff($title_count->all()); 代码应该是这样的。我不确定,我现在不打算测试它。
  • 你是对的。收藏功能正是我所需要的。谢谢。
  • 如果您解决了问题,请回答,或删除您的问题;祝工匠好运。
  • 通过 Collection 对象过滤所有结果是低效的。相反,使用 SQL 仅提取没有计数的标题。

标签: php mysql sql laravel eloquent


【解决方案1】:

使用连接来识别未出现在 title_count 中的标题。

DB::table('titles')->leftJoin('title_count', 'titles.title_id', '=', 'title_count.title_id')
                   ->select('titles.*')
                   ->whereNull('title_count.title_id')
                   ->get();

【讨论】:

    【解决方案2】:

    试试这个

    DB::table('titles')->whereNotExists(function($query)
    {
        $query->select(DB::raw(1))
           ->from('title_count')
           ->whereRaw('title_count.title_id = titles.title_id');
    })->get();
    

    【讨论】:

      【解决方案3】:

      未测试

      DB::table('title_count')
        ->leftJoin('titles as t', 't.title_id', '=', 'title_count.title_id')
        ->select('t.*')
        ->where('t.title_id', '!=', 'title_count.title_id')
        ->get();
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2017-09-02
        • 2018-02-25
        • 1970-01-01
        • 2021-06-02
        • 1970-01-01
        • 2018-01-01
        • 2014-11-12
        • 2016-02-06
        相关资源
        最近更新 更多