I have three models Employer
, Job
, and Transaction
Employer
can have many Job
Job
can have many Transaction
I am trying to use ActiveRecord to get all Employer
that do not have a Transaction
record.
Within my Employer model, I have defined relations to find all jobs and transactions linked to this employer:
/**
* @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");
}
Any ideas on the best way to do this?
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
)
With 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')
)]
);
}
But I didn't test it. Hope it is correct, though. And there might be better solutions.
试试看
$query = MyModel::find()->where(['not in','attribute',$array]);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.