Answer the question
In order to leave comments, you need to log in
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();
<?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']);
}
}
Answer the question
In order to leave comments, you need to log in
$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();
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question