Activerecord关联:创建新对象(查找类) [英] Activerecord-association: create new object (find class)

查看:79
本文介绍了Activerecord关联:创建新对象(查找类)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个带有关系的模型,并且我想实例化一个关系类型的新对象.

I have an model with a relation, and I want to instantiate a new object of the relations type.

示例:一个人有一个公司,而我有一个人对象:现在我 要创建公司对象.

Example: A person has a company, and I have a person-object: now I want to create a company-object.

companyobject的类是在关系中定义的,所以我认为我不需要知道"该类,但是我应该能够要求人员对象为我提供一个新的type实例公司?但是我不知道怎么办.

The class of the companyobject is defined in the relation, so I don't think I should need to 'know' that class, but I should be able to ask the person-object to provide me with a new instance of type company? But I don't know how.

-我认为-与通过关联创建新模型对象,但我使用的是 PHPActiveRecord ,而不是红宝石.

This is -I think- the same question as New model object through an association , but I'm using PHPActiveRecord, and not the ruby one.


其背后的原因:我有一个抽象超类person,并且两个子代与一种类型的company对象具有自己的关系.我需要能够在抽象人员中实例化正确的类.


Reason behind this: I have an abstract superclass person, and two children have their own relation with a type of company object. I need to be able to instantiate the correct class in the abstract person.

一种解决方法是直接从static $has_one数组获取它:

A workaround is to get it directly from the static $has_one array:

$class   = $this::$has_one[1]['class_name'];
$company = new $class;

当然可以通过在数组中搜索关联名称来消除硬编码的数字,但这仍然很丑陋.

the hardcoded number can of course be eliminated by searching for the association-name in the array, but that's still quite ugly.


如果有人知道这在Ruby中是如何实现的,以及phpactiverecord的实现有何不同,我可能会从中得到一些想法?


If there is anyone who knows how this is implemented in Ruby, and how the phpactiverecord implementation differs, I might get some Ideas from there?


一些测试表明,尽管在数组中搜索我的类名"看起来有些怪异,但它对性能没有任何影响,并且在使用中具有足够的功能.


Some testing has revealed that although the "search my classname in an array" looks kinda weird, it does not have any impact on performance, and in use it is functional enough.

推荐答案

您也可以在关系类中使用build_association().
最简单的使用方法是通过模型的__call,即,如果您的关系类似于$person->company,则可以使用
$company = $person->build_company()

实例化公司. 请注意,这也不会在对象之间建立连接"(不会设置$person->company).
或者,您可以使用create_company()代替build_company(),这将保存新记录并将其链接到$ person

You can also use build_association() in the relationship classes.
Simplest way to use it is through the Model's __call, i.e. if your relation is something like $person->company, then you could instantiate the company with
$company = $person->build_company()

Note that this will NOT also make the "connection" between your objects ($person->company will not be set).
Alternatively, instead of build_company(), you can use create_company(), which will save a new record and link it to $person

这篇关于Activerecord关联:创建新对象(查找类)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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