【问题标题】:yii2-Active record with not in conditionyii2 - 不处于状态的活动记录
【发布时间】:2018-04-13 06:24:41
【问题描述】:

我正在处理yii2。我正在使用活动记录来搜索参考号。查询如下

$q = isset($_GET['q']) ? $_GET['q'] : '';
    if(empty($q)) exit;
    $ser = Survey::find()->where("ref_no like '%$q%'")->andWhere(['status'=>1])->asArray()->all();

    return json_encode($ser);

上述查询将获得调查表中的所有参考编号。现在我想添加一个NOT IN 条件。原始查询如下

...... where ref_no LIKE '%$q%' NOT IN (select ref_no from installations where ref_no LIKE '%q%')

如何将其添加到我的活动记录查询中?

任何帮助将不胜感激。

【问题讨论】:

标签: activerecord yii2 yii2-advanced-app notin


【解决方案1】:

您也可以为此使用子查询(假设您的安装表与 Installations 模型相关)

  $subQuery = Installations::find()->select('ref_no')->where("ref_no like '%$q%'");
  $query = Survey::find()->where(['not in', 'ref_no', $subQuery]);
  $models = $query->all();                         

【讨论】:

  • 这是一种更简洁的方法+1,因为我也使用相同的 (⌐■_■)
  • @MuhammadOmerAslam ...谢谢。是基于yii2“指南”的方法
【解决方案2】:

如下更改您的查询:

$ser = Survey::find()->where("ref_no like '%$q%'")
->andWhere(['status'=>1])
->andWhere("ref_no NOT IN (select ref_no from installations where ref_no LIKE '%q%')")
->asArray()->all();

$ser = Survey::find()
->where("ref_no like '%$q%' AND ref_no NOT IN (select ref_no from installations where ref_no LIKE '%q%')")
->andWhere(['status'=>1])
->asArray()->all();

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-12-21
    • 2014-10-08
    • 2011-08-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多