简体   繁体   English

如何附加其他Yii 1.16 ActiveRecord模型?

[英]How Do I Append Additional Yii 1.16 ActiveRecord Models?

I am familiar with using Yii to call records, but how would I go about taking an existing active record model and appending more information to it using a different query? 我对使用Yii调用记录很熟悉,但是如何使用现有的活动记录模型并使用其他查询向其添加更多信息呢?

For example: 例如:

$user = User::model()->findByPk(1);
$user[] = User::model()->findByPk(2);

Basically, I am trying to add model $user1 + $user2. 基本上,我试图添加模型$ user1 + $ user2。 In this type of example, I want to have both users 1 and 2 in the same $user model. 在这种类型的示例中,我希望用户1和2都处于同一$ user模型中。 (I have not actually tried the code above, but I do not think it would work like that.) The information obtain from both requests would be exactly the same format. (我实际上没有尝试过上面的代码,但是我认为它不会那样工作。)从两个请求中获取的信息将完全相同。

Be aware that that I am not trying to get both users. 请注意,我并不想同时获得这两个用户。 I know how to do that. 我知道该怎么做。 In this question, I am attempting to take an existing model and add more data to it to form one model by merging the two models together. 在这个问题中,我试图采用一个现有模型,并通过将两个模型合并在一起,向其中添加更多数据以形成一个模型。

You can do this: 你可以这样做:

$users = array();
$user1 = User::model()->findByPk(1);
$user2 = User::model()->findByPk(2);
array_push($users, $user1);
array_push($users, $user2);

Now $users is an array that contains two objects. 现在$users是一个包含两个对象的数组。

You can use 您可以使用

$users = User::model()->findAllByPk(array(1,2));

which will return and array of usermodels 这将返回和用户模型数组

There is no built in Yii way to do what you are trying to accomplish. 没有内置的Yii方法可以完成您要完成的任务。 Instead, you can your model with some custom enhancements. 相反,您可以对模型进行一些自定义增强。

private $additionalUsers = array();

public function addAdditionalUser($user)
{
    $this->additionalUsers[] = $user;
}

public function getAdditionalUsers()
{
    return $this->additionalUsers;
}

Then you use this as follows: 然后,您可以如下使用它:

$user = User::model()->findByPk(1);
$user->addAdditionalUser(User::model()->findByPk(2));

However, without knowing more of what you mean by "merge" the models, this may or may not be what you are looking for. 但是,在不了解“合并”模型的含义的情况下,这可能不是您想要的。 An example of how you expect to use the merged model would be useful if this answer doesn't suit your needs. 如果此答案不符合您的需求,则说明如何使用合并模型的示例将非常有用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM