简体   繁体   中英

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?

For example:

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

Basically, I am trying to add model $user1 + $user2. In this type of example, I want to have both users 1 and 2 in the same $user model. (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.

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. 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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