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.

图片转代码服务由CSDN问答提供 功能建议

我熟悉使用Yii来调用记录,但是如何使用现有的活动记录模型并附加 使用不同的查询向它提供更多信息?

例如:

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

基本上,我正在尝试添加模型 $ user1 + $ user2。 在这种类型的示例中,我希望在同一$ user模型中同时拥有用户1和2。 (我实际上没有尝试过上面的代码,但我认为它不会那样。)从两个请求获得的信息格式完全相同。

请注意这一点 我不想让两个用户都这么做。 我知道该怎么做。 在这个问题中,我试图通过将两个模型合并在一起来获取现有模型并向其添加更多数据以形成一个模型。

  • 写回答
  • 好问题 提建议
  • 关注问题
  • 收藏
  • 邀请回答

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.

    已采纳该答案
    评论
    解决 无用
    打赏 举报
  • dseslyh6662605 2015-03-13 05:49

    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.

    评论
    解决 无用
    打赏 举报
  • dpo69086 2015-03-13 05:56

    You can use

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

    which will return and array of usermodels

    评论
    解决 无用
    打赏 举报

相关推荐 更多相似问题