【问题标题】:How to create subcollection using Laravel 5 and mongodb如何使用 Laravel 5 和 mongodb 创建子集合
【发布时间】:2016-05-14 23:46:13
【问题描述】:

首先,我是 laravel mongodb 集合的新手,在 laravel 5.0 中使用 jensegers。我想在子集合中形成一个集合,如下所示

    {
  "Uid": 1112,
  "AccountNo": 7620424,
  "Party": {
    "LanguageCode": "en",
    "Type": "individual",
    "Contact": [
      {
        "id" : It will be mongo object id How to create?
        "Type": "default",
        "Person": {
          "FullName": "Test Test"
        },
         {
        "id" : It will be mongo object id How to create?
        "Type": "default",
        "Person": {
          "FullName": "Test Test"
        },
        "MessagingMedium": [
          {
            "Id": It will be mongo object id How to create?
            "Scheme": "mailto",
            "URI": "demo1dd122@gmail.com",
            "Status": "awaiting.registration"
          },
          {
            "Id": It will be mongo object id How to create?
            "Scheme": "mailto",
            "URI": "demo1dd122@gmail.com",
            "Status": "awaiting.registration"
          }
        ]
      }
    ]
  },
}

我有用户档案模型

use Jenssegers\Mongodb\Model as Eloquent;

class UserProfile extends Eloquent  {

    protected $table = 'user_profile';
}

use Jenssegers\Mongodb\Model as Eloquent;

class Contact extends Eloquent  {

    protected $table = 'contact';
}

在尝试将联系人子集合添加到创建的用户配置文件集合后,我尝试创建用户配置文件,如下所示

$user = UserProfile::create(array('Uid' => $uId, 'AccountNo' => $accNo));
$card = Contact::create(['id' => 123]); //contact mongodb Eloquent
$card->userprofile()->save($card); 

但它不起作用,集合没有创建

这是正确的,我不知道有很多,embedsmany colleciton

谁帮帮我

【问题讨论】:

    标签: mongodb laravel collections laravel-5 mongodb-query


    【解决方案1】:

    您必须使用embedsMany relation。这种关系允许您将对象数组(具有自己 ID 的 Eloquent 对象)保存到现有文档中。该关系将完全由 ORM 管理。

    你可以这样声明:

    class UserProfile extends Eloquent
    {
        // No table declaration because this model is only saved in the contact collection
    }
    
    class Contact extends Eloquent
    {
        protected $table = 'contact';
    
        public function userProfiles()
        {
            return $this->embedsMany('UserProfile');
        }
    }
    

    如果您只想将一个对象嵌入到另一个对象中,可以使用 embedsOne 关系。

    在此之前,您应该认真查看软件包文档;)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-08-20
      • 1970-01-01
      • 2018-08-06
      • 2011-12-15
      • 2020-12-07
      • 2017-11-30
      • 2020-09-17
      • 1970-01-01
      相关资源
      最近更新 更多