我有三种型号
Employer可以有许多Job
Transaction可以有许多Employer
我试图使用ActiveRecord来获取所有没有Job记录的Job
在我的雇主模式中,我定义了寻找与此雇主相关的所有工作和交易的关系:

/**
 * @return \yii\db\ActiveQuery
 */
public function getJobs() {
    return $this->hasMany(Job::className(), ['employer_id' => 'employer_id']);
}

/**
 * @return \yii\db\ActiveQuery
 */
public function getTransactions() {
    return $this->hasMany(Transaction::className(), ['job_id' => 'job_id'])->via("jobs");
}

有什么好办法吗?

最佳答案

SQL语言:

SELECT employer.*
FROM   employer
WHERE  employer.employer_id NOT IN
(
  SELECT employer.employer_id
  FROM employer
    INNER JOIN job         ON employer.employer_id = job.employer_id
    INNER JOIN transaction ON           job.job_id = transaction.job_id
)

有了Yii2:
function getThoseWithoutTransaction() {
    return Employer::find()->where(['not in', 'employer_id',
        (new Query())
            ->select('employer.employer_id')
            ->from('employer')
            ->innerJoin('job', 'employer.employer_id = job.employer_id')
            ->innerJoin('transaction', 'job.job_id = transaction.job_id')
        )]
    );
}

但我没有测试。不过,希望是对的。也许会有更好的解决方案。

关于php - 使用ActiveRecord的Yii2查询生成器,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/30366321/

10-13 02:38