I'm upgrading a big project form Yii1 to Yii2. I'm having some problems regarding to ORM.
I have several relation declared in the following fashion(basically a copy-paste from the guidebook ):
class Order extends \yii\db\ActiveRecord {
/* other code */
public function getAffiliate()
{
return $this->hasOne(Affiliate::className(), ['id_affiliate' => 'affiliate_id']);
}
Whenever I try to echo or w/e $order->affiliate->name
; I get the following error:
yii\base\ErrorException: Trying to get property of non-object
I've got no experience with Yii1 what so ever. Something weird about this project is the database. All tables start with yii_tablename
and id's are: id_tablename
. Was that normal for Yii1 and could this be causing the issue above?
Edit : When I execute the function like so: $order->getAffilate()
it returns an ActiveQuery WITHOUT the data from the affiliate.
When I execute the following:
$order->getBillingAddress()->one();
I get a weird error:
Getting unknown property: app\models\Order::billing
return $this->hasOne(Affiliate::className(), ['id_affiliate' => 'affiliate_id']);
It's mean that when you call $order->affiliate
yii2 will find in Affiliate
table on id_affiliate
field current Order
affiliate_id
value and selected one
value.
Check that you have right field names and database have right data.
When you call $order->affiliate
you will get Affiliate
object. But if you call $order->getAffiliate()
you will get ActiveQuery
object.
I found a solution. One which I don't really like though, but it does the job. Was reading this thread: link .
Kartik V
The problem is clearly in uniqueness in naming your relation and your model attribute. In your User model, you have an attribute named role and you also have a relation getter named getRole.
So I changed the name of the getter like so:
public function getOrderAffiliate()
{
return $this->hasOne(Affiliate::className(), ['id_affiliate' => 'affiliate_id']);
}
And that fixed the issue. Never had this issue before and wonder why this happened though.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.