【问题标题】:yii2 add where condition model for every findyii2 为每个查找添加 where 条件模型
【发布时间】:2016-03-09 12:51:15
【问题描述】:

在 Yii2 中,我尝试更改 ActiveRecord 模型,以便每次应用程序运行 find() 或 findAll() 时,它还会在条件中添加额外的 where。

例如,应用程序调用 Stock 模型的 find() 方法:

$UsersStockFound = Stock::Find()
->where(['stockActive' => 1]);

所以,这就是我想要发生的事情,我希望模型在用户看到结果之前添加一个额外的条件。 假设我已经将租户引用存储在 $this->tenant 下 所以我想将它添加到上面的查询中,但通过模型无缝。

->AddWhere(['tenantId' => $this->tenantId]);

所以换句话说,整体将是这样的:

$UsersStockFound = Stock::Find()
->where(['stockActive' => 1]);
->AddWhere(['tenantId' => $this->tenant]);

【问题讨论】:

    标签: activerecord model find yii2 multi-tenant


    【解决方案1】:

    您可以简单地覆盖模型中的 find() 方法:

    public static function find()
    {
        return parent::find()->where(['storeActive' => 1]);
    }
    

    Reference

    【讨论】:

    • 这也会影响 FindAll 还是我需要覆盖它?
    • @MarkJohnson。只需在查询中添加all(),否则您必须覆盖findAll()。因为两者是不同的方法。
    • 谢谢大家的帮助!
    • @soju。谢谢。找到了findAll() include find()
    • 有一个问题,如果我使用 Stock::Find()->All() 它似乎忽略了 ->where(['storeActive' => 1])
    【解决方案2】:

    以上解决方案都不适合我.. 如果您使用“where”,无论您做什么覆盖,find 都将不起作用..

    我找到了自己的解决方案,如下所示,它将覆盖所有 ORM 调用。

    class model extends \yii\db\ActiveRecord
    {
    
        public static function find()
        {
                  
            return new CustomActiveRecordQuery(get_called_class());
        }
    
    }
    class CustomActiveRecordQuery extends ActiveQuery
    {
        // ...
            public function prepare($builder)
        {
                $this->andWhere(['status' => 'Active']);
                return parent::prepare($builder);
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2020-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-10-29
      • 1970-01-01
      • 2016-10-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多