Doctrine2 findby on a Many-to-One mapping - doctrine-orm

I have two entities with a Unidirectional Many-to-One mapping.
Here's Product:
use Doctrine\Common\Collections\ArrayCollection;
/**
* #Entity
* #Table(name="Product")
* #gedmo:TranslationEntity(class="GPos_Model_Translation_ProductTranslation")
*/
class GPos_Model_Product extends GPos_Doctrine_ActiveEntity {
/**
* #Id #Column(type="integer")
* #GeneratedValue
*/
protected $id;
/**
* #ManyToMany(targetEntity="GPos_Model_Category")
* #JoinTable(name="products_categories",
* joinColumns={#JoinColumn(name="product_id", referencedColumnName="id")},
* inverseJoinColumns={#JoinColumn(name="category_id", referencedColumnName="id")}
* )
*/
protected $categories;
public function __construct() {
$this->categories = new ArrayCollection();
}
public function addCategory(GPos_Model_Category $category) {
if (!$this->categories->contains($category))
$this->categories->add($category);
}
}
As you can see, $categories is an ArrayCollection of GPos_Model_Category entities.
Now what?
Well now I'd like to retrive all products that are in a given category and also all products that are NOT in a given category.
I've tried $products = GPos_Model_Product::findByCategories($category->getId());
but that only gave me
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 '= '1'' at line 1 and $category's ID is 1 so I guess it's not the way to go. Anyone knows how to deal with that ?
Thank you!

I finally found out how to select all products that are in a category thanks to https://stackoverflow.com/a/9808277/1300454.
I tweaked his solution a bit so I could pass an array of Category entities and it would find all products that are within these categories. If you give more than one entity it will return any product that is in at least one of the given categories.
Here's my tweak (I located this function in my Product entity):
/**
*
* Takes an array of GPos_Model_Category entities as parameter and returns all products in these categories
* #param array $categories
*/
public static function findByCategories($categories) {
$categoryArray = array();
foreach ($categories as $category) {
array_push($categoryArray, $category->getId());
}
$qb = Zend_Registry::get('entityManager')->createQueryBuilder();
$qb ->select('p')
->from('GPos_Model_Product', 'p')
->leftJoin('p.categories', 'c')
->andWhere($qb->expr()->in('c.id', $categoryArray));
return $qb->getQuery()->execute();;
}
Here's how you call it:
$products_cat = GPos_Model_Product::findByCategories(array($category));
In this case $category is an entity alone that's why I put it in an array before giving it to the function.
And here is the way you find products that are not in a given category or list of category:
/**
*
* Takes an array of GPos_Model_Category entities as parameter and returns all products not in these categories
* #param array $categories
*/
public static function findByNotCategories($categories) {
$categoryArray = array();
foreach ($categories as $category) {
array_push($categoryArray, $category->getId());
}
$qb = Zend_Registry::get('entityManager')->createQueryBuilder();
$qb2 = Zend_Registry::get('entityManager')->createQueryBuilder();
$qb->select('p')
->from('GPos_Model_Product', 'p')
->where($qb->expr()->notIn('p.id',
$qb2->select('p2.id')
->from('GPos_Model_Product', 'p2')
->leftJoin('p2.categories', 'c')
->andWhere($qb->expr()->in('c.id', $categoryArray))
->getDQL()
));
return $qb->getQuery()->execute();
}
This is actually using a subselect. I'm selecting all products id that are in the given category (that's the subselect) then I'm selecting all products that are not in the result of the subselect. My job here is done!

Related

How to join column and target entity manually in manytoone relation?

I have two fields : account_type_id and account_id.
How can i manually map doctrine TargetEntity to join Company Entity if accountTypeId = 1 OR join User Entity if account_type_id = 2 ?
<?php
/** #Entity */
class Accounts
{
// 1= Company, 2 = User
private $accountType;
/**
* #ManyToOne(targetEntity="Companies")
*/
private $company;
/**
* #ManyToOne(targetEntity="Users")
*/
private $user;
//...
}
Unfortunately, joining different columns on the fly cannot be done automatically, but you can have both fields set as nullable and only set the correct one when persisting the Account entity.
This would be the annotation:
/**
* #ORM\ManyToOne(targetEntity="Users", inversedBy="users")
* #ORM\JoinColumn(name="user_id", referencedColumnName="id", nullable=true)
*/
private $user;
Keep in mind that nullable=true is the default anyway, I'm just being specific here.
If you want to go defensively about this, you can have an additional check in getter
/**
* #return User
* #throws \Exception
*/
public function getUser()
{
if ($this->accountType !== 2) {
throw new \Exception("Entity is not of type 'user'");
}
return $this->user;
}

How to select rows which have both items in ManyToMany relation

Let's assume i have "News" entity which has got ManyToMany "Tag" relation
class News
{
/**
* #ORM\ManyToMany(targetEntity="App\Domain\Entity\Vocabulary\Tag")
*/
private Collection $tags;
}
And i have such query:
public function getList(
array $tags = null,
): Query {
if (null !== $tags) {
$qb->andWhere('nt.id IN (:tags)');
$qb->setParameter('tags', $tags);
}
}
The problem is when i pass ["Tag1", "Tag2"] it selects news that have either the first tag or the second, but not both at the same time. How can i rewrite the query to select news which have both tags at the same time?
Some things to notice first:
For doctrine annotations it is possible to use the ::class-constant:
use App\Domain\Entity\Vocabulary\Tag;
class News
{
/**
* #ORM\ManyToMany(targetEntity=Tag::class)
*/
private Collection $tags;
}
If the $tags array is empty doctrine will throw an exception because an empty value set is invalid SQL, at least in mysql:
nt.id IN () # invalid!
Now to the problem:
With the SQL-aggregation functions COUNT and GROUP BY we can count the number of tags for all news. Together with your condition for the allowed tags, the number of tags per news must be equal to the number of tags in the tags array:
/**
* #var EntityManagerInterface
*/
private $manager;
...
/**
* #param list<Tag> $tags - Optional tag filter // "list" is a vimeo psalm annotation.
*
* #return list<News>
*/
public function getNews(array $tags = []): array
{
$qb = $this->manager
->createQueryBuilder()
->from(News::class, 'news')
->select('news')
;
if(!empty($tags)) {
$tagIds = array_unique(
array_map(static function(Tag $tag): int {
return $tag->getId();
}) // For performance reasons, give doctrine ids instead of objects.
); // Make sure duplicate tags are handled.
$qb
->join('news.tags', 'tag')
->where('tag IN (:tags)')
->setParameter('tags', $tagIds)
->addSelect('COUNT(tag) AS HIDDEN numberOfTags')
->groupBy('news')
->having('numberOfTags = :numberOfTags')
->setParameter('numberOfTags', count($tags))
;
}
return $qb
->getQuery()
->getResult()
;
}

Doctrine: Is it possible to preload child/related N:N entities with single DB query?

Given the following parent-child entities, how can I preload all child C entities with only single database query when I have many P (already loaded) enties?
/**
* #ORM\Entity
**/
class P {
/** #var Collection #ORM\ManyToMany(targetEntity="C") */
public $childs;
}
/**
* #ORM\Entity
**/
class C {
/** #var int #ORM\Column(type="integer") **/
public $v;
}
Test case, this code should not issue any additional database query once preloaded.
foreach ($ps as $p) {
foreach ($p->childs as $child) { $dummy = $child->v; }
}
The following query preloads all N:N child entities in one query.
note: performance is only about 0.5 times better than foreach over non preloaded data. Probably because the P entity (in my applied case) contained a lot of fields.
$em->createQueryBuilder()->select('p', 'c')
->from(P, 'c')
->leftJoin('l.childs', 'c') // preload
->where('p.id IN (:ps)')->setParameter('ps', $ps)
->getQuery()->getResult();

Two one-to-many relationship with reference table (Doctrine 2, ZF2)

I've a problem with my many-to-many relation. I want to have access to the reference table for a querybuilder query. With a many-to-many relation I don't have access to my reference table, so I've set up two one-to-many relationships. My structure look likes:
User ---> UserUserCategory <--- UserCategory
The above structure has two one-to-many relationships and are working fine with the database. When I have a user with the following data in the database (in UserUserCategory):
Table User
ID | Name
1 | Bart
2 | Gerard
Table Category
ID | Name
1 | Officer
2 | Medic
Table UserUserCategory
User | Category
1 | 1
2 | 2
So Bart is an Officer and Gerard is a Medic. But when I want to retrieve the data, it said that Bart is the Medic, and Gerard has a "null" value in the category.
My User-entity:
/**
* Entity Class representing a post of our User module.
*
* #ORM\Entity
* #ORM\Table(name="user")
* #ORM\Entity(repositoryClass="User\Repository\UserRepository")
*
*/
class User extends zfcUser implements UserInterface
{
/**
* Categories from user
*
* #ORM\OneToMany(targetEntity="User\Entity\UserUserCategory", mappedBy="user_id", cascade={"remove", "persist"})
* #var UserUserCategory
* #access protected
*/
protected $user_usercategories;
//name & user_id comes here
/**
* Constructor to make a new ArrayCollection for addresses
*
*
*/
public function __construct()
{
$this->user_usercategories = new ArrayCollection();
}
/**
* #param Collection $categories
*/
public function addUserUserCategories(Collection $user_usercategories)
{
foreach ($user_usercategories as $user_usercategorie) {
$user_usercategorie->setUser($this);
$this->user_usercategories->add($user_usercategorie);
}
}
/**
* #param Collection $categories
*/
public function removeUserUserCategories(Collection $user_usercategories)
{
foreach ($user_usercategories as $user_usercategorie) {
$user_usercategorie->setUser(null);
$this->user_usercategories->removeElement($user_usercategorie);
}
}
/**
* #return Collection
*/
public function getUserUserCategories()
{
return $this->categories;
}
}
My UserCategory-entity:
/**
* A User category entity.
* #ORM\Entity
* #ORM\Table(uniqueConstraints={#ORM\UniqueConstraint(name="unique_name_parentId", columns={"name", "parent_id"})})
* #ORM\HasLifecycleCallbacks
*/
class UserCategory extends Category
{
/**
* User_usercategories
*
* #ORM\OneToMany(targetEntity="User\Entity\UserUserCategory", mappedBy="category_id")
* #var UserUserCategory
* #access protected
*/
protected $user_usercategories;
/**
* Constructor
*/
public function __construct()
{
$this->user_usercategories = new ArrayCollection();
}
/**
* #param Collection $categories
*/
public function addUserUserCategories(Collection $user_usercategories)
{
foreach ($user_usercategories as $user_usercategorie) {
$user_usercategorie->setCategory($this);
$this->user_usercategories->add($user_usercategorie);
}
}
/**
* #param Collection $categories
*/
public function removeUserUserCategories(Collection $user_usercategories)
{
foreach ($user_usercategories as $user_usercategorie) {
$user_usercategorie->setCategory(null);
$this->user_usercategories->removeElement($user_usercategorie);
}
}
/**
* #return Collection
*/
public function getUserUserCategories()
{
return $this->categories;
}
}
My UserUserCategory-entity:
/**
* Entity Class representing a post of our User_UserCategory entity.
*
* #ORM\Entity
* #ORM\Table(name="user_usercategory")
*
*/
class UserUserCategory
{
/**
* User with a category
*
* #ORM\ManyToOne(targetEntity="User\Entity\User", inversedBy="user_usercategories")
* #ORM\JoinColumn(name="user_id", referencedColumnName="user_id", nullable=false, onDelete="CASCADE")
* #ORM\Id
*
* #var User
* #access protected
*/
protected $user_id;
/**
* Category from user
*
* #ORM\ManyToOne(targetEntity="User\Entity\UserCategory", inversedBy="user_usercategories")
* #ORM\JoinColumn(name="category_id", referencedColumnName="id", nullable=false, onDelete="CASCADE")
* #ORM\Id
*
* #var Category
* #access protected
*/
protected $category_id;
public function getUser()
{
return $this->user;
}
/**
* Set User
*
* #param User $user
* #return User
*/
public function setUser(User $user = null)
{
//die('setUser');
$this->user = $user;
return $this;
}
public function getCategory()
{
return $this->category;
}
/**
* Set Category
*
* #param Category $category
* #return Category
*/
public function setCategory(Category $category = null)
{
$this->category = $category;
return $this;
}
}
When I execute the following line, it gives back the wrong result. The wrong category pops up:
\Doctrine\Common\Util\Debug::dump($this->getEntityManager()->find('User\Entity\User', '49')->user_usercategories);
die;
Result:
array(1) {
[0]=>
object(stdClass)#452 (3) {
["__CLASS__"]=>
string(28) "User\Entity\UserUserCategory"
["user_id"]=>
string(16) "User\Entity\User"
["category_id"]=>
string(24) "User\Entity\UserCategory"
}
}
In the category_id is the medic printed, I expect the officer to get back.
In my other user, (id=60) the category_id field is "null". So it look likes Doctrine skips the first input in my UserUserCategory, starts with the second and can't get the last category anymore.
No offence, but I find your code very hard to read. I would suggest you to do few corrections and that might even help you in solving the problem.
1: Naming: Instead of UserCategory, rename it to Category. If your Category will have different types, create new column "type" with values from constansts like
class Category
{
const TYPE_USER = 1 ;
....
2: Instead of addCategories(Collection $array), do singular version like
public function addCategory(Category $category)
{
$reference = new UserCategory() ;
$reference->setUser($this) ;
$reference->setCategory($category) ;
$this->user_categories->add($reference) ;
}
public function removeCategory(Category $category)
{
foreach($this->user_categories as $reference) {
if ( $reference->getCategory() === $category )
$this->user_categories->removeElement($reference) ;
}
}
Symfony2 automaticaly recognizes methods like this. Even if your relation is plural (like categories), s2 will find singularified addCategory and removeCategory methods.
To get array of categories, use this:
public function getCategories()
{
$categories = new ArrayCollection() ;
foreach($this->user_categories as $reference) {
$categories->add( $reference->getCategory() ) ;
}
return $categories ;
}
If you do it like this, you will probably solve the problem you have.

Doctrine 2 - Insert new item in database

I'm trying to make something very simple.. but I do wrong, and I don't know what is the problem. Just I'm trying to insert new item to database with Doctrine 2:
$favouriteBook = new UserFavouriteBook;
$favouriteBook->user_id = 5;
$favouriteBook->book_id = 8;
$favouriteBook->created_at = new DateTime("now");
$this->_em->persist($favouriteBook);
$this->_em->flush();
As you can see.. is very simple, but that, give me next error:
Error: Message: SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'user_id' cannot be null
Obviosly, if I make a "dump" before "persist" and "flush" of $favouriteBook, all looks be correct..
This is my "favouriteBook" entity:
/** #Column(type="integer")
* #Id
*/
private $user_id;
/** #Column(type="integer")
* #Id
*/
private $book_id;
/**
* #ManyToOne(targetEntity="Book", inversedBy="usersFavourite")
* #JoinColumn(name="book_id", referencedColumnName="id")
*/
private $book;
/**
* #ManyToOne(targetEntity="User", inversedBy="favouriteBooks")
* #JoinColumn(name="user_id", referencedColumnName="id")
*/
private $user;
/** #Column(type="datetime") */
private $created_at;
public function __get($property) {
return $this->$property;
}
public function __set($property, $value) {
$this->$property = $value;
}
Anyone can image what is the problem? .. I don't know what else try.. Thanks
I think what beberlei is saying is that within your favouriteBook entity, you don't need to define the user_id and book_id as class properties, b/c the book and user properties you have set already recognize these as the relevant join columns. Also, your attempt to persist the favouriteBook entity failed because you need to set the book and user entity associations within the favouriteBook entity, not the foreign keys. So it would be:
$favouriteBook = new UserFavouriteBook;
$favouriteBook->book = $book;
$favouriteBook->user = $user;
$favouriteBook->created_at = new DateTime("now");
$this->_em->persist($favouriteBook);
$this->_em->flush();
You are mapping foreign keys and the associations. You have to modify the association not the foreign key field. Its bad-practice to map them both, you should remove $book_id and $user_id completly.