Doctrine orderBy with PostgreSQL json column (could not identify an equality operator for type json) - postgresql

I have two entities Export and ExportItem. One of the columns in Export entity is config type json (that is only column with json type in my database).
Part of Export entity:
/**
* #ORM\Column(type="json", nullable=true)
*/
protected $config;
/**
* #var ArrayCollection|ExportItem[]
* #ORM\OneToMany(targetEntity="Entity\ExportItem", mappedBy="export", cascade={"persist", "remove"}, fetch="EXTRA_LAZY")
*/
protected $items;
Part of ExportItem entity:
/**
* #var Export
* #ORM\ManyToOne(targetEntity="Entity\Export", inversedBy="items")
*/
protected $export;
I want to order Exports per number of attached ExportItems, but next query throw me error "could not identify an equality operator for type json"
$this->createQueryBuilder('o')
->join('o.suit', 's')
->where('s.id = :suitId')
->setParameter('suitId', $suit->getId())
->select('COUNT(i) AS HIDDEN nbrItems', 'o.id')
->leftJoin('o.items', 'i')
->orderBy('nbrItems', $orderDir)
->groupBy('o');

I found a solution. Just need to add
->groupBy('o.id');
in the query

Related

Add refrences to MongoDB schema within Symfony project

I'm trying to create MongoDB database with some references within Symfony.
In my context I have 2 documents Customer and Meeting, One Customer can have Many Meeting so that what I did :
Meeting.php
<?php
namespace FrontOfficeBundle\Document;
use Doctrine\ODM\MongoDB\Mapping\Annotations as MongoDB;
/**
* #MongoDB\Document
*/
class Meeting
{
/**
* #MongoDB\Id
* #MongoDB\ReferenceOne(targetDocument="Customer")
*/
protected $id;
/**
* #MongoDB\Field(type="timestamp")
*/
protected $creationDate;
...
Customer.php
<?php
namespace FrontOfficeBundle\Document;
use Doctrine\ODM\MongoDB\Mapping\Annotations as MongoDB;
/**
* #MongoDB\Document
*/
class Customer
{
/**
* #MongoDB\Id()
* #MongoDB\ReferenceMany(targetDocument="Meeting")
*/
protected $id;
/**
* #MongoDB\Field(type="string")
*/
protected $username;
...
and then when I run the command line:
php bin/console doctrine:mongodb:schema:update
I got :
No identifier/primary key specified for Document 'FrontOfficeBundle\Document\Meeting'. Every Document must have an identifier/primary key.
I tried by using #MongoDB\UniqueIndex() but no way.
I think that #MongoDB\Id is supposed as an identifier !!!
Versions
Symfony 3.2
MongoDB 3.4.4
Any ideas ?
Thanks you.
Finally I found a solution, first I added a field called $meetings in the document Customer and an other $customer in the document meeting like this :
Customer.php
/**
* #MongoDB\ReferenceMany(targetDocument="meeting", mappedBy="customer")
*/
protected $meetings;
Meeting.php
/**
* #MongoDB\ReferenceOne(targetDocument="customer", inversedBy="meetings")
*/
protected $customer;
Then run the command line to generate setters and getters:
php bin/console doctrine:mongodb:generate:documents mybundleBundle
And when I run a fixtures (Creating one customer then its meeting), everything work fine, you'll notice that the relationship 1 to many has been defined in your document (I'm using compass to display mongoDB) as a One-to-Squillions model (for more details about 1-to-N relationship : (https://www.mongodb.com/blog/post/6-rules-of-thumb-for-mongodb-schema-design-part-1) that's mean the son document (meeting) contains the reference of the parent as shown below :
Customer
Meeting
In MongoDB the #MongDB/Id is a primary key and the foreign key and never try to define references to this unique field.
Thanks for your attention.

Invalid text representation: 7 ERROR: invalid input syntax for uuid: "test"

I'm using Symfony 3.2 with doctrine and postgresql.
I've created an entity with a uuid as primary key.
My entity definition:
/**
* Booking
*
* #ORM\Table(name="booking")
* #ORM\Entity(repositoryClass="AppBundle\Repository\BookingRepository")
* #ORM\EntityListeners({"AppBundle\EventListener\BookingListener"})
*/
class Booking {
/**
* #var string
*
* #ORM\Column(type="guid")
* #ORM\Id
* #ORM\GeneratedValue(strategy="UUID")
*/
private $id;
}
In my controller I have a show action like this:
/**
* #Route("booking/{id}", name="booking_show")
* #Method({"GET"})
*/
public function showAction(Request $request, Booking $booking) {
...
}
Everything seems to work fine, but when I try to load a route putting an wrong value as an ID (i.e. /booking/hello123), I receive a:
SQLSTATE[22P02]: Invalid text representation: 7 ERROR: invalid input syntax for uuid: "hello123"
Instead I would expect a 404.
Is there a way to capture this exception and redirect to a 404 page?
You can make use of Route Requirements - you can specify what conditions your parameter need to match to "qualify" to a certain route. This requirement is a regex, so all you need to do is to write a regex for an UUID
/**
* #Route("booking/{id}", name="booking_show", requirements={"id": "[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}"})
* #Method({"GET"})
*/
public function showAction(Request $request, Booking $booking) {
...
}
NOTE: Regex used above is just first result I found in Google for UUID regex, I didn't verify if it works
In the end if your id does not match regex, it does not match route and you should get 404.
you need to change the showaction
/**
* #Route("booking/{id}", name="booking_show")
* #Method({"GET"})
*/
public function showAction(Request $request,$bookingID) {
$em = $this->getDoctrine()->getManager();
$booking = $em->getRepository('AppBundle:Entity')->find(bookingID);
if(!$booking)
$this->createNotFoundException('No entity found with id :'.$bookingID);
...
}

Persisting a document suddenly stops returning next identifier value (ALNUM strategry)

I have Symfony 2.6 application and using doctrine-odm-bundle 3.0.2 (doctrine-odm: 1.1.2, mongodb: 1.4.0).
My document has referenceMany and referenceOne in attributes and when I create new instance of it, fill fields and persist - it goes fine in the begining. I can create few nearly empty documents, with referenced document(s) or without and it works fine. At some point I am trying to add new item in the database and getting an error:
E11000 duplicate key error collection: test.Product index: _id_ dup key: { : 0 }
The message is clear - I can see that there was a document added to the collection with id = 0, therefore second one can't go -> duplicate entry. But why it suddenly starts to return "0" for id? Even though, I checked doctrine_increment_ids collection - counter for id is being incremented. But $product->getId() becomes "0" after persist.
If I drop the database and start all over - it works, I can still add new products in the collection. Let's say I successfully created 12 products. Creating 13th resulting a document with id=0 being persisted in the collection. 14th fails with duplicate error.
Can you please help to troubleshoot or suggest an idea where does it go wrong?
P.S> I am not considering an upgrade of Symfony2 (at this point) neither as doctrine-odm-bundle (it depends on newer Symfony2 as well) - migration efforts are quite high and I am not sure it will fix the issue. First I want to find out the root cause.
// Document Product
/**
* #MongoDB\Document
* #MongoDB\HasLifecycleCallbacks
*/
class Product
{
/** #MongoDB\Id(strategy="ALNUM", type="int") */
protected $id;
/**
* #Gedmo\ReferenceOne(type="entity", class="Entity\User", inversedBy="products", identifier="userId")
*/
protected $user;
/**
* #MongoDB\Field(name="user_id", type="int")
*/
protected $userId;
/**
* #MongoDB\ReferenceMany(
* targetDocument="Picture",
* discriminatorMap={"file" = "File", "picture" = "Picture"},
* discriminatorField="discr",
* defaultDiscriminatorValue="picture"
* )
* #Assert\Valid
*/
protected $pictures;
...
}
// Entity User
/**
* User entity
* #ORM\Entity
* #ORM\Table(name="users")
*/
class User
{
/**
* #ORM\Id
* #ORM\Column(type="integer")
* #ORM\GeneratedValue(strategy="AUTO")
*/
protected $id;
/**
* #var ArrayCollection $textures
*
* #Gedmo\ReferenceMany(type="document", class="Document\Product", mappedBy="user")
*/
protected $products;
...
}
// Document Picture
/**
* #MongoDB\Document
* #MongoDB\InheritanceType("SINGLE_COLLECTION")
* #MongoDB\DiscriminatorField("discr")
* #MongoDB\DiscriminatorMap({"file" = "File", "picture" = "Picture"})
* #MongoDB\DefaultDiscriminatorValue("picture")
* #MongoDB\HasLifecycleCallbacks
*/
class Picture
{
/**
*
* #MongoDB\Id(strategy="ALNUM", type="int")
*/
protected $id;
/**
* #MongoDB\ReferenceOne(targetDocument="Product")
*
* #var Product $product
*/
protected $product;
...
}
Documentation reading always helps (generation strategies). Basically, strategy="ALNUM" and type="int" just can't go together :)
Change strategy to INCREMENT and remove type="int" if you want to have integers in your _id.
Or you can change type to string to continue with _id being an alphanumeric string.

zend2 + doctrine 2 Uncaught exception 'Doctrine\Common\Annotations\AnnotationException' $jobId does not exist

I am new to zend 2 and Doctrine 2. I tried to create an entity class but got the following message:
Fatal error: Uncaught exception
'Doctrine\Common\Annotations\AnnotationException' with message
'[Semantical Error] The annotation "#Doctrine\ORM\Mapping\jobId" in
property Workers\Entity\Jobsought::$jobId does not exist, or could not
be auto-loaded
Below is the entity class
namespace Workers\Entity;
use Doctrine\ORM\Mapping as ORM;
use Zend\InputFilter\InputFilter;
use Zend\InputFilter\Factory as InputFactory;
use Zend\InputFilter\InputFilterAwareInterface;
use Zend\InputFilter\InputFilterInterface;
/**
*
*
* #ORM\Entity
* #ORM\Table(name="worker_main_jobsort")
* #property int $jobId
*/
class Jobsought implements InputFilterAwareInterface
{
protected $inputFilter;
/**
* #ORM\jobId
* #ORM\Column(type="integer")
* #ORM\GeneratedValue(strategy="AUTO")
*/
protected $jobId;
/**
* Magic getter to expose protected properties.
*
* #param string $property
* #return mixed
*/
public function __get($property)
{
return $this->$property;
}
/**
* Magic setter to save protected properties.
*
* #param string $property
* #param mixed $value
*/
public function __set($property, $value)
{
$this->$property = $value;
}
}
Any ideas why the ORM cannot map it? The table exist in my database.
Also just started out using the two of these combined - but think I know what your issue is.
First off, you can't try specifying any "strange" (according to doctrine strange) annotations without using the #ignore directive.
Secondly, I think you're trying to say with #property int $jobId that "$jobId" is your PK? Well you're already doing so when you say #ORM\GeneratedValue(strategy="AUTO"), telling doctrine to map jobid to be your PK. Also, I read somewhere that adding name="job_id" to your #Column annotation is good practice, but don't quote me on that. Guess it doesn't really matter.
Hope this helps!
Edit -
My bad, also missed that you need to remove #ORM\jobId as it's not a valid doctrine annotation (jobId that is). Just specify it as #ORM\Id and you should be fine.

Symfony2 valid constraint on form element does not show custom error message

I am constructing a form for users to submit a DMCA complaint, and one of the design requirements is to allow them to enter one or more URLs. To that end, I've created an entity (DMCAComplaint), and a child entity (DMCAComplaintURL) which is joined to DMCAComplaint in a Doctrine OneToMany relationship.
In order to validate the URL entries via regex, I have the following assertion set up:
// src: Bundle/Event/DMCAComplaintURL.php
/**
* #var string
*
* #ORM\Column(name="url", type="string", length=255, nullable=false)
* #Assert\Regex(
* pattern="/(https?:\/\/)?([\w].)*example.com(\/.*)?/"),
* message="Please enter a URL within our site"
* )
*/
protected $url;
And in the complaint:
// src: Bundle/Entity/DMCAComplaint.php
/**
* #var \DMCAComplaintURL
*
* #ORM\OneToMany(targetEntity="DMCAComplaintURL", mappedBy="dmcaComplaint", cascade={"persist"})
* #ORM\JoinColumns({
* #ORM\JoinColumn(name="id", referencedColumnName="dmca_complaint_id")
* })
* #Assert\Valid
*/
protected $urls;
While the assertion works, it only gives the following error: This value is not valid. I would like it to have a custom message, as outlined in the DMCAComplaintUrl $url property. Is there a way to make this bubble up to the Valid assertion? or can I use something else to get what I need?
Set error_bubbling to true on your form field:
http://symfony.com/doc/current/reference/forms/types/text.html#error-bubbling