在Yii中的活动记录的模型文件中添加新属性 [英] add new property in model file of a active record in Yii

查看:219
本文介绍了在Yii中的活动记录的模型文件中添加新属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是Yii框架的新手,并且有一个问题.

I am new in Yii framework and have a question.

我有一个名为"node"的表,其中包含以下字段:

I have a table named 'node' which has these fields:

  • id
  • 名称
  • parent_id

parent_id也包含此表中也存在的节点的父代ID.

parent_id contain id of parent of a node which exist in this table too.

我已经使用Gii界面创建了模型,控制器和视图文件.在视图文件中显示了父级的ID,但我想显示父级名称而不是其ID.

I have created model,controller and view files using Gii interface. In view files id of parent is shown but I want to display parent name instead of its id .

我想也许我需要在此表的模型类中添加一个公共属性,以便可以通过视图文件中的-> parent_name访问它.

I guess maybe I need to add a public property in model class of this table, so I would be access to it via ->parent_name in view files.

我该怎么办?我应该更改哪些文件?

How can I do it ? what files should I change ?

推荐答案

您应该与父节点有关系.

You should have a relation to your parent node.

因此,在您的Node :: relations函数中,您应该具有类似以下内容:

So in your Node::relations function, you should have something like:

'parent' => array(self::BELONGS_TO, 'Node', 'parent_id'),

要从孩子那里获得此值,可以执行以下操作(假设您的孩子节点变量名为$ childNode):

To get this value from your child, you can do (assuming your child node variable is named $childNode):

echo $childNode->parent->name;

如果您真的想做...

If you really want to be able to do...

$childNode->parent_name;

...由于某种原因,您可以像这样在Node模型中创建一个属性:

... for some reason, you can create a property in your Node model like this:

public function getParent_name()
{
    if ($this->parent == null)
        return '';

    return $this->parent->name;
}

现在您可以致电...

Now you can call...

$childNode->parent_name;

OR

$childName->getParent_name();

获取父节点的名称.

这篇关于在Yii中的活动记录的模型文件中添加新属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆