如何使用Laravel 5和mongodb创建子集合

时间:2016-02-05 05:12:41

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

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

    {
  "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"
          }
        ]
      }
    ]
  },
}

我有userprofile模型

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';
}

尝试将联系人子集合添加到创建的userprofile集合后,我尝试创建用户个人资料,如下所示

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

但它没有用,而且这个集合没有创建

这是正确的,我不知道abount hasmany,embedsmany colleciton

任何人帮助我

1 个答案:

答案 0 :(得分:0)

您必须使用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关系。

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