Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

yii2 hasOne relation work wrong

Tags:

php

yii2

I have 2 tables : users and favorite the following :

users table

favorite

now I establish a relation between them like the following in Favorite model

public function getUser()
{
    return $this->hasOne(User::className(), ['id', 'user_favorited']);
}

in Controller I find a list of user's favorites

public function actionGetList()
{
    $favorite = Favorite::find()->where([
              'user_favoriting' => Yii::$app->user->id
          ])->all();
    foreach ($favorite as $key => $item) {
        # code...
        echo "<pre>"; var_dump($item->user); echo "<br/>"; die('123');
    }
    return $favorite;
}

But when I make a request to this action I get an error

Column not found: 1054 Unknown column '0' in 'where clause'\nThe SQL being executed was: SELECT * FROM `users` WHERE (`0`, `1`) IN ((12, 80))",

Please help me!

like image 835
Hoang NK Avatar asked Aug 16 '26 10:08

Hoang NK


1 Answers

According to documentation you have to use:

public function getUser()
{
    return $this->hasOne(User::className(), ['id' => 'user_favorited']);
}
like image 61
Touqeer Shafi Avatar answered Aug 18 '26 23:08

Touqeer Shafi



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!