I'm try to serialize a MongoDB document with embedded documents within Symfony 2.1. I am using the JMSserializer and Mongodb-odm bundles.
I have the following Documents entities.
// Blog
namespace App\DocumentBundle\Document;
use Symfony\Component\Validator\Constraints as Assert;
use Doctrine\ODM\MongoDB\Mapping\Annotations as MongoDB;
use JMS\SerializerBundle\Annotation\Type;
/**
* #MongoDB\Document(repositoryClass="App\DocumentBundle\Repository\BlogRepository")
*/
class Blog {
/**
* #MongoDB\Id
*/
protected $id;
/**
* #MongoDB\String
* #Assert\NotBlank()
*/
protected $title;
/**
* #MongoDB\string
* #Assert\NotBlank()
*/
protected $blog;
/**
* #MongoDB\EmbedMany(targetDocument="Tag")
*/
private $tags;
/**
* #MongoDB\Timestamp
*/
protected $created;
/**
* #MongoDB\Timestamp
*/
protected $updated;
}
and
// Tag
namespace App\DocumentBundle\Document;
use Doctrine\ODM\MongoDB\Mapping\Annotations as MongoDB;
/**
* #MongoDB\EmbeddedDocument
*/
class Tag {
/**
* #MongoDB\String
*/
protected $name;
}
An ArrayCollection type is generated for the tag attribute, but the JMSSerializer bundle doesn't like it. If I change the tag to #MongoDB\String and regenerate the Blog document,
then serialization occurs, but not with #MongoDB\EmbedMany(targetDocument="Tag") set.
Do I need to specify some of the JMSSerializer annotated attributes allow embedded document to also be serialized?
You have to configure the expected type for JMSSerializer
Annotation :
/**
* #MongoDB\EmbedMany(targetDocument="Tag")
* #Type(ArrayCollection<App\DocumentBundle\Document\Tag>)
*/
private $tags;
Yaml :
tags:
expose: true
type: ArrayCollection<App\DocumentBundle\Document\Tag>
Related
I need implement FOSUserBundle using ORM database and FOSMessageBundle using MongoDB (ODM database). Is it posible?
I configure FOSUserBundle using ORM and works.
I am triying to configure FOSMessageBundle using the documentation https://github.com/FriendsOfSymfony/FOSMessageBundle/blob/master/Resources/doc/01b-odm-models.md the problem it is here:
/**
* #MongoDB\ReferenceOne(targetDocument="Acme\UserBundle\Document\User")
*/
protected $sender;
I don´t have Acme\UserBundle\Document\User, I have Acme\UserBundle\Entity\User .
If I put Acme\UserBundle\Entity\User don´t work.
I try to use http://doctrine-mongodb-odm.readthedocs.org/en/latest/cookbook/blending-orm-and-mongodb-odm.html but I need help.
Another option it is create a duplicate User table in MongoDB but I don't know how I can do this.
Thanks for your solution Nawdal Serrar.
I read the documentation and try this. Don`t work, can you help me please?
Message.php
/**
* #MongoDB\Document
*/
class Message extends BaseMessage{
/**
* #MongoDB\Id
*/
protected $id;
/**
* #MongoDB\EmbedMany(targetDocument="xxx\MensajeriaBundle\Document\MessageMetadata")
*/
protected $metadata;
/**
* #MongoDB\ReferenceOne(targetDocument="xxx\MensajeriaBundle\Document\Thread")
*/
protected $thread;
/**
* #Gedmo\ReferenceMany(type="entity", class="xxx\WebBundle\Entity\usuarios", mappedBy="senderMongo")
*/
protected $sender;
public function __construct()
{
$this->metadata = new \Doctrine\Common\Collections\ArrayCollection();
$this->createdAt = new \DateTime();
}
}
MessageMetadata.php
/**
* #ODM\EmbeddedDocument
*/
class MessageMetadata extends BaseMessageMetadata
{
/**
* #Gedmo\ReferenceMany(type="entity", class="xxx\WebBundle\Entity\usuarios", mappedBy="participantMesssageMongo")
*/
protected $participant;
}
Thread.class
/**
* #MongoDB\Document
*/
class Thread extends BaseThread
{
/**
* #MongoDB\Id
*/
protected $id;
/**
* #MongoDB\ReferenceMany(targetDocument="xxx\MensajeriaBundle\Document\Message")
*/
protected $messages;
/**
* #MongoDB\EmbedMany(targetDocument="xxx\MensajeriaBundle\Document\ThreadMetadata")
*/
protected $metadata;
/**
* #Gedmo\ReferenceMany(type="entity", class="xxx\WebBundle\Entity\usuarios", mappedBy="participantsMongo")
*/
protected $participants;
/**
* #Gedmo\ReferenceMany(type="entity", class="xxx\WebBundle\Entity\usuarios", mappedBy="createdByMongo")
*/
protected $createdBy;
}
ThreadMetadata.php
/**
* #ODM\EmbeddedDocument
*/
class ThreadMetadata extends BaseThreadMetadata
{
/**
* #Gedmo\ReferenceMany(type="entity", class="xxx\WebBundle\Entity\usuarios", mappedBy="participantThreatMongo")
*/
protected $participant;
}
usuarios.php
/**
* #Gedmo\ReferenceOne(type="document", class="xxx\MensajeriaBundle\Document\Message", inversedBy="sender", identifier="senderId")
*/
private $senderMongo;
/**
* #ORM\Column(type="string", nullable=true)
*/
private $senderId;
/**
* #Gedmo\ReferenceOne(type="document", class="xxx\MensajeriaBundle\Document\MessageMetadata", inversedBy="participant", identifier="participantMessageId")
*/
private $participantMessageMongo;
/**
* #ORM\Column(type="string", nullable=true)
*/
private $participantMessageId;
/**
* #Gedmo\ReferenceOne(type="document", class="xxx\MensajeriaBundle\Document\Thread", inversedBy="participants", identifier="participantsId")
*/
private $participantsMongo;
/**
* #ORM\Column(type="string", nullable=true)
*/
private $participantsId;
/**
* #Gedmo\ReferenceOne(type="document", class="xxx\MensajeriaBundle\Document\Thread", inversedBy="createdBy", identifier="createdById")
*/
private $createdByMongo;
/**
* #ORM\Column(type="string", nullable=true)
*/
private $createdById;
/**
* #Gedmo\ReferenceOne(type="document", class="xxx\MensajeriaBundle\Document\ThreadMetadata", inversedBy="participant", identifier="participantThreadId")
*/
private $participantThreadMongo;
/**
* #ORM\Column(type="string", nullable=true)
*/
private $participantThreadId;
This is what you need, you can reference relationships between ODM and ORM entities https://github.com/Atlantic18/DoctrineExtensions/blob/master/doc/references.md
I have this document Scheme:
use Doctrine\ODM\MongoDB\Mapping\Annotations as MongoDB;
/**
* #MongoDB\Document(collection="users") *
*/
class Markers
{
/**
* #MongoDB\Id
*/
protected $id;
/**
* #MongoDB\Float
*/
protected $lat;
/**
* #MongoDB\Float
*/
protected $lng;
/**
* #MongoDB\String
*/
protected $title;
}
What I want is having index on $title field and $lat and $lng
how do you suggest I should work this out ?
Do I have to tell the document that these fields are indexes or , running the command in Mongo shell is sufficient ?
Thanks !
You can define indexes in Mongo shell and make it independent from code implementation. Your database would be accessible from different systems and mantain consistency in its administration.
¿Have you considered the use of geospacial indexes for lng and lat?
I am using Symfony2 with Doctrine 2.
I have 5 entities in my application.
Book
Keyword (Bidirectional, should fetch all books having particular keyword)
Author (Bidirectional, should fetch all books having particular author(s))
Category (Bidirectional, should fetch all books falling into particular category)
BookExtra (Unidirectional, In Book Entity, should fetch BookExtra data)
Each book can have many keywords
Each book can have many authors
Each book can fall into a single category
Each book have exactly one BookExtra record.
The keyword and author tables should contain unique values
When a new Book is added, if the Author(s) and Keyword(s) exists, the respected Author ID and Keyword ID should be assigned to the Book, and if it doesn't exist, the new records will be created and the respected ID should be assigned to the Book.
I have the following Entity Classes:
Book.php
namespace Acme\StoreBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* Book
*
* #ORM\Table(name="book")
* #ORM\Entity
*/
class Book {
/**
* #var integer
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
protected $id;
/**
* #var string
*
* #ORM\Column(name="isbn", type="string", length=16)
*/
protected $isbn;
/**
* #var string
*
* #ORM\Column(name="title", type="string", length=255)
*/
protected $title;
/*
* #ORM\OneToOne(targetEntity="BookExtra")
* #ORM\JoinColumn(name="extra_id", referencedColumnName="id")
*
* ********* OR *********
* *********What should go HERE*********
*
*/
protected $bookextra;
/*
* #ORM\ManyToMany(targetEntity="Author", inversedBy="books")
* #ORM\JoinTable(name="authors_books")
*/
protected $author;
/*
* #ORM\OneToOne(targetEntity="Category")
* #ORM\JoinColumn(name="category_id", referencedColumnName="id")
*/
protected $category;
}
BookExtra.php
namespace Acme\StoreBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* BookExtra
*
* #ORM\Table(name="book_extra")
* #ORM\Entity
*/
class Detail {
/**
* #var integer
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
protected $id;
/**
* #var string
*
* #ORM\Column(name="data", type="string", length=255)
*/
protected $data;
}
Author.php
namespace Bookhut\BookBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* Author
*
* #ORM\Table(name="author")
* #ORM\Entity
*/
class Author {
/**
* #var integer
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
protected $id;
/**
* #var string
*
* #ORM\Column(name="name", type="string", length=100)
*/
protected $name;
// **********What should go HERE*********
protected $books;
}
Keyword & Category Entities are similar to Author Entity
The Problem is that, when i generate schema with cli, it never generates Relationships/Associations.
And what should be the proper Relationships/Associations for Book & Author Entity
I searched for this problem and proper Relationships/Associations
I found this:
Symfony2 app/console not generating properties or schema updates for Entity Relationships/Associations
Saving onetoone relation entities
doctrine2: in a one-to-many bidirectional relationship, how to save from the inverse side?
But it didn't help me.
Can somebody give an example of this type of Relationships/Associations and insert operations?
For author->books:
/**
* #ManyToMany(targetEntity="Author", inversedBy="books")
* #JoinTable(name="authors_books",
* joinColumns={#JoinColumn(name="book_id", referencedColumnName="id")},
* inverseJoinColumns={#JoinColumn(name="author_id", referencedColumnName="id")}
* )
*/
protected $author;
For books->authors
/**
* #ManyToMany(targetEntity="Book", mappedBy="author")
*/
protected $books;
See http://docs.doctrine-project.org/en/latest/reference/association-mapping.html#many-to-many-bidirectional for documentation of many-to-many
See http://docs.doctrine-project.org/en/latest/reference/association-mapping.html for full documentation of associations
EDIT
Is assume all your entities will have setters and getters.
// Create new Author object
$Author = new Author();
// Use setters to set all attributes for this author
// Create new book
$Book = new Book();
// Use setters to set all attributes for book
// Attach book to author
$Author->addBook($Book);
$Book->addAuthor($Author);
The addBook and addAuthor will look like this:
// Inside author entity
public function addBook(Book $Book) {
$this->books->add($Book);
}
// Inside book entity
public function addAuthor($Author) {
$this->authors->add($Author);
}
And add a constructor to both the author and book entities:
public function __construct() {
$this->books = new ArrayCollection();
}
public function __construct() {
$this->authors = new ArrayCollection();
}
Have a look at the documentation to see more examples:
http://docs.doctrine-project.org/projects/doctrine-orm/en/latest/reference/working-with-associations.html
I need help. Here is the situation. I am using Symfony2 + FOSRestBundle, I created my Entity-Classes to store my data in MySQL via Doctrine. I also wrote all the Controllers to get the data and directly translate it to my database. That works fine.
namespace Stat\ContentBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* #ORM\Entity
* #ORM\Table(name="agegroups")
*/
class Table
{
* #ORM\Column(name="id", type="smallint")
* #ORM\Id
* #ORM\GeneratedValue(strategy="IDENTITY")
*/
protected $id;
/**
* #ORM\Column(name="description", type="string", length=50)
* #Type("string")
*/
protected $description;
Now I do want to use the same Entity declaration and extend it with some more information for usage with MongoDB. I want to store my data in MySQL and additionally in MongoDB. To reuse the code with the mongodb-odm-bundle I have to use the namespace Document - and that's just the beginning of the problems. If I would want to reuse my Controllers I would have to rewrite that code for MongoDB as well.
namespace Stat\ContentBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
use Doctrine\ODM\MongoDB\Mapping\Annotations as MongoDB;
/**
* #MongoDB\Document
* #ORM\Entity
* #ORM\Table(name="agegroups")
*/
class Table
{
* #ORM\Column(name="id", type="smallint")
* #ORM\Id
* #MongoDB\Id
* #ORM\GeneratedValue(strategy="IDENTITY")
*/
protected $id;
/**
* #ORM\Column(name="description", type="string", length=50)
* #MongoDB\String
* #Type("string")
*/
protected $description;
/**
* #ORM\Column(name="mySqlOnly", type="string", length=50)
* #Type("string")
*/
protected $mySqlOnly;
/**
* #MongoDB\String
*/
protected $mongoDbOnly;
Is there an easy way to use a Doctrine-database schema for both document-based and relational databases?
Maybe this helps:
Blending the ORM and MongoDB ODM
It is quote easy to use a database nybrid with Doctrine2 since you have an entity- plus an documentmanager.
I've been trying to get an existing project working on local copy but have been countering alot of problems with the ODM and the dependencies.
I'm encountering this Sluggable issue :
[Semantical Error] The annotation "#Gedmo\Mapping\Annotation\Sluggable" in property
Cereals\ProductBundle\Document\Category\Specialty::$name does not exist, or could not be
auto-loaded.
And my Cereals...\Specialty file is such:
<?php
namespace Cereals\ProductBundle\Document\Category;
use Doctrine\ODM\MongoDB\Mapping\Annotations as MongoDB;
use Gedmo\Mapping\Annotation as Gedmo;
/**
* #MongoDB\Document(collection="Specialty",
repositoryClass="Cereals\ProductBundle\Repository\SpecialtyRepository")
*/
class Specialty
{
/**
* #MongoDB\Id(strategy="auto")
*/
protected $id;
/**
* #Gedmo\Sluggable
* #MongoDB\Index(order="asc")
* #MongoDB\String
*/
protected $name;
/**
* #MongoDB\String
* #MongoDB\UniqueIndex
* #Gedmo\Slug
*/
protected $slug;
/**
* #MongoDB\String
*/
I understand from Googling that there are some syntax updates for doctrine 2.1.x and I've used the new annotations for the #Gedmo\Mapping\Annotation\Sluggable here too.
Still the Semantical Error turns up.
Can anyone point some directions ? Thanks !
The #Gedmo\Sluggable annotation does not exisit. If you look in this folder, you will see this anottation is not implemented.
Actually, You can define your class like that:
<?php
namespace Cereals\ProductBundle\Document\Category;
use Doctrine\ODM\MongoDB\Mapping\Annotations as MongoDB;
use Gedmo\Mapping\Annotation as Gedmo;
/**
* #MongoDB\Document(collection="Specialty",
repositoryClass="Cereals\ProductBundle\Repository\SpecialtyRepository")
*/
class Specialty
{
/**
* #MongoDB\Id(strategy="auto")
*/
protected $id;
/**
* #MongoDB\Index(order="asc")
* #MongoDB\String
*/
protected $name;
/**
* #MongoDB\String
* #MongoDB\UniqueIndex
* #Gedmo\Slug(fields={"name"})
*/
protected $slug;
}
The #Gedmo\Slug annotation needs the properties which will be used for the slug generation.