Anton Abramov
Anton Abramov

Reputation: 2321

Yii 2, active record, with

how can i get a set of data, based on condition in relation table?

In Yii 1 i could use with() and 'on' statement. This doesn't work in Yii 2, or i can't find any good example. For example in Yii 1 i could write this:

$criteria = new CDbCriteria();
$criteria->with = array('works'=>array('on' => 'works.user_id=t.id AND (works.work_id=$SOMEVALUE OR ...)'));

I tried something like this (userRight is my relation):

Foo::find()->with(['userRight'=>['on'=>['user_r'=>$this->id]]]);

Is there any solution in Yii 2?

Upvotes: 2

Views: 10392

Answers (2)

Aditya Dharma
Aditya Dharma

Reputation: 718

if in your table have a relation and using gii to generate models, controller and view it will make function for the relation. if no you can make function to declare relation 2 tables in model

public function getWorks()
{
    return $this->hasOne(Works::className(), ['id' => 'works_id']);
}

if hasMany just flip id.

and call the function

Foo::find()->joinWith('works')->all();

Upvotes: 0

Alex
Alex

Reputation: 8072

From official example:

$orders = Order::find()->innerJoinWith([
    'customer' => function ($query) {
        $query->where('customer.created_at > ' . (time() - 24 * 3600))
              ->onCondition(['category_id' => 1]);
    }
])->all();

See this link

Upvotes: 1

Related Questions