doulu5717 2015-03-12 22:19
浏览 18
已采纳

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

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.

  • 写回答

3条回答 默认 最新

  • dtv55860 2015-03-13 06:32
    关注

    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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?