2

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?

2 Answers 2

3

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.

Sign up to request clarification or add additional context in comments.

Comments

1

Try with

$query = MyModel::find()->where(['not in','attribute',$array]);

2 Comments

This doesn't work. I'm looking to get all Employers which don't have transactions (through job)
If in the $array you have the distinct Employers which have transation and in attribute the employer_id this is the righit solution

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.