如何在 Yii2 中使用 orOnCondition 定义关系

how to define a relationship in Yii2 with orOnCondition

我正在将数据库中的更改记录到名为 audit_field 的 table 中。对于给定的模型,我想检索该模型的所有 audit_field 以及一些相关模型。

例如:

<?php
class Job extends ActiveRecord
{
    public function getAuditFields()
    {

        $link = []; // what do I put here to get "1=1" ?

        return $this->hasMany(AuditField::className(), $link)
            ->orOnCondition([
                'audit_field.model_id' => $this->job_id, 
                'audit_field.model_name' => get_class($this),
            ])
            ->orOnCondition([
                'audit_field.model_id' => ArrayHelper::map($this->getJobTeches()->all(), 'id', 'id'),
                'audit_field.model_name' => 'app\models\JobTech',
            ]);
    }
    public function getJobTeches()
    {
        return $this->hasMany(JobTech::className(), ['job_id' => 'job_id']);
    }
}

我想要的:

SELECT * FROM audit_field WHERE (...my or conditions...);
// or
SELECT * FROM audit_field WHERE (1=1) AND (...my or conditions...);

我得到的:

SELECT * FROM audit_field WHERE (1=0) AND (...my or conditions...)

找到答案,不要使用 hasMany,而只是 return 和 ActiveQuery:

<?php
class Job extends ActiveRecord
{
    public function getAuditFields()
    {
        return AuditField::find()
            ->orOnCondition([
                'audit_field.model_id' => $this->job_id, 
                'audit_field.model_name' => get_class($this),
            ])
            ->orOnCondition([
                'audit_field.model_id' => ArrayHelper::map($this->getJobTeches()->all(), 'id', 'id'),
                'audit_field.model_name' => 'app\models\JobTech',
            ]);
    }
}