Reputation: 315
In my database I have: region table with fileds
-id
-name
and flower table
-id
-name
-region - this is ID from ragion table
in my Flower model I have method
public function getRegion()
{
return $this->hasOne(Region::className(), ['id' => 'region']);
}
and now when I try to use it like this
$flower->region->name
I got error Trying to get property of non-object
$flower->region
return ID of region. How can I get name of region by use
$flower->region->name
?
update: when I use gii to generate Flower model I got this method:
public function getRegion0()
{
return $this->hasOne(Region::className(), ['id' => 'region']);
}
I dont get it. Why I cant use simple getRegion()
Upvotes: 0
Views: 604
Reputation: 22174
You cannot use the same name for relation as for DB attribute. Attributes from database have precedence over methods (this answer explains how value for property will be searched). If you have attribute with region
as name, it will be used instead of attribute/relation provided by method getRegion()
. Gii is smart enough to generate relation wit different name - although region0
is not really good name, it works.
In your case the best way would be to rename region
column to region_id
- column name becomes more clear and you get rid of names conflicts between relation and attribute names.
Upvotes: 5