A
A
AlexSer2018-01-30 10:34:42
Yii
AlexSer, 2018-01-30 10:34:42

Why can't I reproduce a dynamic query in Yii2?

Hi all. I do by analogy from the documentation
customer = Customer::findOne(123);


// SELECT * FROM `order` WHERE `customer_id` = 123 AND `subtotal` > 200 ORDER BY `id`
$orders = $customer->getOrders()
->where(['>', 'subtotal', 200] )
->orderBy('id')
->all();

My Model
<?php

namespace frontend\models;

use Yii;


class Case extends \yii\db\ActiveRecord
{
    /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return 'case';
    }
    public function rules()
    {
        return [
            [['date'], 'safe'],
            [['userID', 'historyID'], 'integer'],
            [['historyID'], 'exist', 'skipOnError' => true, 'targetClass' => History::className(), 'targetAttribute' => ['historyID' => 'id']],
        ];
    }
    public function attributeLabels()
    {
        return [
            'id' => 'ID',
            'date' => 'Date',
            'userID' => 'User ID',
            'historyID' => 'History ID',
        ];
    }
    public  function getUsers(){
        return $this->hasMany(Users::className(), ['id' => 'user_id'])
            ->viaTable('history', ['id' => 'historyID']);
    }
}

But when I do $case=Case::find(); and call $query=$case->getUsers()->where(['like','dr','1990'])->all();
it just doesn't see the getUsers() property.
The question is what I do not understand and how to do it right?

Answer the question

In order to leave comments, you need to log in

[[+comments_count]] answer(s)
E
Evgeny Bukharev, 2018-01-30
@AlexSer

$case=Case::find()
This function will return an ActiveQuery object, not an ActiveRecord, to execute getUsers(), you need to call this function on the Case object, for example:

$case=Case::finOne($id);
$result=$case->getUsers()->where(['like','dr','1990'])->all();

either way
Here you need to take into account table aliases, as well as correctly specify filtering by dr.
What do you initially need to get in the request? All cases along with users?

V
vksee, 2018-02-01
@vksee

First of all, you should first pay attention to the fact that the attribute name userID appears everywhere, and for some reason user_id appears in getUsers() :
public function getUsers() {
return $this->hasMany(Users::className(), ['id ' => ' user_id '])
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question