【问题标题】:eloquent where not in query?雄辩哪里不问?
【发布时间】:2015-06-20 23:57:11
【问题描述】:

我正在尝试用 eloquent 构建以下 sql 查询。该查询为我提供了 table_a 中的所有记录,这些记录在 ids 列表中,但未出现在 table_b 中。

select * from table_a 
where id in (1,2,3)
   and id not in 
      (select tablea_id from table_b 
       where tablea_id in (1,2,3))

那么我该如何在 eloquent 中做到这一点?我想避免使用原始查询。

//does not work
TableA::whereIn('id',$ids)
   ->whereNotIn('id', TableB::select('tabla_id')->whereIn($ids));

【问题讨论】:

  • whereNotIn 将数组作为第二个参数... RTFM
  • @pc-shooter 不正确,它也需要关闭!
  • @lukasgeiter OOpps,对我来说也是如此(重新)阅读 F* 手册...谢谢指点!

标签: laravel-4 eloquent


【解决方案1】:

要运行子查询,您必须传递一个闭包:

TableA::whereIn('id',$ids)
      ->whereNotIn('id', function($q){
          $q->select('tabla_id')
            ->from('tableb');
            // more where conditions
      })
      ->get();

【讨论】:

  • @pc-shooter 非常感谢。下次随意编辑这些明显的错别字;)
  • 认为我不能只编辑其他用户帖子中的一个字符?
  • 啊,我明白了……我已经超过了代表限制,所以我暂时忘记了
  • 这样就好了,会有很多“just-code-formatting-or-one-two-chars-editing”
猜你喜欢
  • 2014-04-14
  • 2017-08-22
  • 1970-01-01
  • 1970-01-01
  • 2019-09-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-03-31
相关资源
最近更新 更多