Access to the field of the associated table at the "hasOne/hasMany " in Yii2
-
I want to.
$this->title
remove the name of the category from the associated table.public function getCategory() { return $this->hasOne(Category::className(), ['id' => 'category_id']); }
How can you be used instead
category_id
Could be set.category.name
Like GridView, there's just a way to describe it in the attributes.category.name
and he'll take what he needs. Can we also be here?$this->title = $model->category_id;
-
Example https://github.com/yiisoft/yii2/blob/master/docs/guide-ru/db-active-record.md ...
https://github.com/yiisoft/yii2/blob/master/docs/guide-ru/db-active-record.md#%D0%9E%D0%B1%D1%8A%D1%8F%D0%B2%D0%BB%D0%B5%D0%BD%D0%B8%D0%B5-%D1%81%D0%B2%D1%8F%D0%B7%D0%B5%D0%B9- :
public function getOrders() { return $this->hasMany(Order::className(), ['customer_id' => 'id']); }
https://github.com/yiisoft/yii2/blob/master/docs/guide-ru/db-active-record.md#%D0%94%D0%BE%D1%81%D1%82%D1%83%D0%BF-%D0%BA-%D1%81%D0%B2%D1%8F%D0%B7%D0%BD%D1%8B%D0%BC-%D0%B4%D0%B0%D0%BD%D0%BD%D1%8B%D0%BC-
After you've announced your connections, you can access the links with the communication name. This occurs in the same way as access to the object ' s properties by means of the communication method. For that reason, we call him communications♪ For example:
// SELECT * FROM `customer` WHERE `id` = 123 $customer = Customer::findOne(123);
// SELECT * FROM
order
WHEREcustomer_id
= 123
// $orders - это массив объектов Order
$orders = $customer->orders;
Info: When you call a connection to the name
xyz
by ghettergetXyz()
♪, you have the opportunity to access your properties ♪xyz
like the object. Remember that the name of the link is sensitive to the register.In your case, it would look like:
$model->category->name;