J
J
JohnDaniels2017-08-14 14:48:39
Yii
JohnDaniels, 2017-08-14 14:48:39

How to filter data by related table?

Hello.
There are User and Company models.

class User extands ActiveRecord{
//
public function getCompany()
    {
        return $this->hasOne(Company::className(), ['user_id' => 'id']);
    }

    public function getIsCompany()
    {
        return $this->company ? true : false;
    }
}

I want to get a list of users who don't have a Company, i.e. something like this
$query = User::find();

$dataProvider = new ActiveDataProvider([
   'query' => $query,
]);
    
$query->where(['company' => false]);

And I get the error that
Unknown column 'company'.

How to do it right?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
M
Maxim Fedorov, 2017-08-14
@JohnDaniels

$dataProvider = new ActiveDataProvider([
   'query' => $query,
]);
    
$query->joinWith('company')->where(['is','user_id',null]);

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question