i want to use this:
$query = $this->_doctrine->createQueryBuilder()
->select('u')
->from('\Entities\Users', 'l')
->leftJoin('l.userentities', 'u')
->getQuery();
return $info = $query->getResult();
and my users entity is:
namespace Entities\Users;
/**
* #Entity
* #Table(name="users")
* #HasLifecycleCallbacks
*/
class Users extends \Entities\AbstractEntity
{
/**
* #Id #Column(name="userid", type="integer")
* #GeneratedValue(strategy="AUTO")
*/
protected $userid;
/** #Column(name="itemid", type="integer") */
protected $itemid;
}
and my user entities entity class contains:
namespace Entities\Users;
/**
* #Entity
* #Table(name="userentities")
* #HasLifecycleCallbacks
*/
class Userentities extends \Entities\AbstractEntity
{
/**
* #Id #Column(name="entityid", type="integer")
* #GeneratedValue(strategy="AUTO")
*/
protected $entityid;
/** #Column(name="userid", type="integer") */
protected $userid;
/** #Column(name="crb", type="string") */
protected $crb;
}
i tried put this into the entity but no joy
* #OneToMany(targetEntity="Users", inversedBy="userid")
* #JoinColumn(name="userid", referencedColumnName="userid")
1 user has many user entities..
and i get this error:
Error: Class Entities\Users has no association named Users
i just want to do a left join with users to usersentities..
how can i doa left join?
Try putting this annotation in your Userentities class for the $userid field:
/**
* #var Entities\Userentities
* #ManyToOne(targetEntity="Users", inversedBy="userentities", cascade={"persist"})
*/
private $userid;
and this annotation in your Users class with a new field called $userentities:
/**
* #var \Doctrine\Common\Collections\ArrayCollection
* #OneToMany(targetEntity="Userentities", mappedBy="userid", cascade={"persist", "remove"})
*/
private $userentities;
Related
I have two ODM document One is Item contain
class Items {
/**
* #MongoDB\Field(name="item_name", type="string")
*/
protected $itemName;
}
and another document is
class ItemLocation {
/**
* #var
* #MongoDB\ReferenceOne(targetDocument="Items")
*/
private $item;
/**
* #MongoDB\Field(name="priority", type="integer")
*/
protected $priority;
/**
* #var
* #MongoDB\ReferenceOne(targetDocument="Location")
*/
private $location;
}
How I can get all items left join with item location which is filter by location and order by priority.
In order to get all items left join with item location you can use the inversedBy and mappedBy options.
The document Items will be like this:
class Items {
/**
* #MongoDB\Field(name="item_name", type="string")
*/
protected $itemName;
/**
* #MongoDB\ReferenceMany(targetDocument=ItemLocation::class, mappedBy="item")
*/
private $items_items;
}
The document ItemLocation will be like this:
class ItemLocation
{
/**
* #var
* #MongoDB\ReferenceOne(targetDocument="Items", inversedBy="items_items")
*/
private $item;
/**
* #MongoDB\Field(name="priority", type="integer")
*/
protected $priority;
/**
* #var
* #MongoDB\ReferenceOne(targetDocument="Location")
*/
private $location;
}
In order to generate getter and setter use:
php bin/console doctrine:mongodb:generate:documents appBundle
The controller will be like this:
$dm = $this->get('doctrine_mongodb')->getManager();
$repository = $dm->getRepository('Items:Categorie');
$i = $repository->findOneBy(array('id' => 'example'));
$items = $i->getItemsItems();
Read more here.
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 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 finally set up my mapping for my two tables, i can now join tables via the querybuilder..
however, i cant add data to the join column, its keeps saying null.
my account entity:
namespace Entities\Users;
/**
* #Entity(repositoryClass="\Entities\Users\Account")
* #Table(name="account")
* #HasLifecycleCallbacks
*/
class Account extends \Entities\AbstractEntity {
/**
* #Id #Column(name="accid", type="bigint",length=15)
* #GeneratedValue(strategy="AUTO")
*/
protected $accid;
/** #Column(name="name", type="string", length=255) */
protected $name;
/** #Column(name="profileid", type="integer", length=255) */
protected $profileid;
/** #Column(name="acc_added_date", type="datetime", columnDefinition="datetime", nullable=true) */
private $acc_added_date;
/**
* #ManyToOne(targetEntity="Profiledetails")
* #JoinColumn(name="profileid", referencedColumnName="pid")
*/
private $account;
and my profiledetails entity:
namespace Entities\Users;
/**
* #Entity(repositoryClass="\Entities\Users\Profiledetails")
* #Table(name="profiledetails")
* #HasLifecycleCallbacks
*/
class Profiledetails extends \Entities\AbstractEntity {
/**
* #Id #Column(name="pid", type="bigint",length=15)
* #GeneratedValue(strategy="AUTO")
*/
protected $accid;
/** #Column(name="name", type="string", length=255) */
protected $name;
/** #Column(name="profileid", type="integer", length=255) */
protected $profileid;
/** #Column(name="acc_added_date", type="datetime", columnDefinition="datetime", nullable=true) */
private $acc_added_date;
/**
* #OneToMany(targetEntity="Account", mappedBy="account")
* #JoinColumn(name="pid", referencedColumnName="pid")
*/
private $stances;
i use to use :
$postdata array ('name'=>'jason');
$entity =new \Entities\Users\Account;
$obj->setData($postdata);
$this->_doctrine->persist($obj);
$this->_doctrine->flush();
$this->_doctrine->clear();
and it doesnt add.. what the way to add data to the parent table where all linked tables get updated? because before i could enter a profileid and now its null because i used it as a the joined column..
Linked objects can be "updated" if you setup cascade=[persist] in your relationship definitions. You also need #mappedBy and #inversedBy to be set for both sides of the relations. Basically #mappedBy is set to the oneToMany side (called inverse side) and #inversedBy to the manyToOne side (called owning side)
http://www.doctrine-project.org/docs/orm/2.0/en/reference/association-mapping.html#one-to-many-bidirectional
The proper way is basically
//assume $this->_doctrine is instance of EntityManager
$user = new User();
$user->setEmail('john#example.com');
$account = new Account();
$account->setName('john');
$account->setUser($user);
$user->addAccount($account); //if no cascade set
$this->_doctrine->persist($account);
$this->_doctrine->persist($user); //if no cascade set
$this->_doctrine->flush();
http://www.doctrine-project.org/docs/orm/2.0/en/reference/working-with-associations.html#establishing-associations
I'm trying to do a join between 2 tables, but I get this error:
Message: SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '' at line 1
This is the code:
Page model
public function __construct()
{
$this->pages_meta = new \Doctrine\Common\Collections\ArrayCollection();
}
/**
* #var integer $id
* #Id #Column(type="integer")
* #GeneratedValue
*/
private $id;
/**
* #var integer $layout
* #Column(type="string")
*/
private $layout;
/**
* #var string $name
* #Column(type="string")
*/
private $name;
/**
* #var string $title
* #Column(type="string")
*/
private $title;
/**
* #var string $slug
* #Column(type="string")
*/
private $slug;
/**
* #var string $options
* #Column(type="integer")
*/
private $content_id;
/**
* #var integer $user_id
* #Column(type="integer")
*/
private $user_id;
/**
* #var string $created_at
* #Column(type="datetime")
*/
private $created_at;
/**
* #var string $language
* #Column(type="string")
*/
private $language;
/**
* #OneToMany(targetEntity="Default_Model_PageMeta", mappedBy="page_id")
* #JoinColumn(name="id", referencedColumnName="page_id")
*/
private $meta;
... (getters and setters)
PageMeta Model
/**
* #var integer $id
* #Id #Column(type="integer")
* #GeneratedValue
*/
private $id;
/**
* #var integer $page_id
* #Column(type="integer")
*/
private $page_id;
/**
* #var integer $key
* #Column(type="string")
*/
private $key;
/**
* #var integer $value
* #Column(type="string")
*/
private $value;
... (getters and setters)
The join Syntax
$doctrine = Zend_Registry::get('doctrine');
$request = Zend_Controller_Front::getInstance()->getRequest();
$qb = $doctrine->_em->createQueryBuilder()
->select('p, m')
->from('Default_Model_Page', 'p')
->join('p.meta', 'm');
$query = $qb->getQuery();
$page = $query->getResult();
Zend_Debug::dump($page); die;
Any idea what I'm doing wrong?
Thanks in advance!
It doesn't look like you have told Doctrine how to associate a Page model with a PageMeta model. I can guess that the foreign key in the table for PageMeta is page_id, but that doesn't appear anywhere in your annotations.
In the PageMeta model, try:
/**
* The page
*
* #var Default_Model_Page
* #OneToOne(targetEntity="Default_Model_Page")
* #JoinColumn(name="page_id", referencedColumnName="id")
*/
private $page;
Then in your query, you should be able to do:
$qb = $doctrine->_em->createQueryBuilder()
->select('p, m')
->from('Default_Model_PageMeta', 'm')
->join('m.page', 'p');
Not tested, but something like this should work.
Don't map the db columns you need for a relation as both #Column and #ManyToOne (or OneToOne), but always choose one. For most relations you'll want the association mappings (#ManyToOne, etc) and need to drop the #Column.
Doctrine will behave very erratic if you use both.
/**
* #Entity
*/
class Page
{
/**
* #OneToMany(targetEntity="PageMeta", mappedBy="page")
*/
private $meta;
public function __construct() {
$this->meta = new \Doctrine\Common\Collections\ArrayCollection();
}
}
/**
* #Entity
*/
class PageMeta
{
// Remove the property $page_id
/**
* #ManyToOne(targetEntity="Page", inversedBy="meta")
* #JoinColumn(name="page_id", referencedColumnName="id")
*/
private $page;
}
You can find more info on assiciations here.