is there any chance to check if the year is unique in datetime format?
I've set my unique validator from doctrine validator for unique entity, but it checks for complete date, so if i keep the same year and change the date, it will pass the validation.
use Doctrine\ORM\Mapping as ORM;
use Symfony\Bridge\Doctrine\Validator\Constraints\UniqueEntity;
/**
* Movie
*
* #UniqueEntity("name", message="This movie is already in the base")
* #UniqueEntity("releaseDate", message="Best movie from this year is already in the base")
* #ORM\Table(name="movie")
* #ORM\Entity(repositoryClass="AppBundle\Repository\MovieRepository")
*/
class Movie
{
/**
* #var string
*
* #ORM\Column(name="name", type="string", length=255, unique=true)
*/
private $name;
/**
* #var \DateTime
*
* #ORM\Column(name="release_date", type="date", unique=true)
*/
private $releaseDate;
Related
I've been working on a multi users web application using symfony 3.4 framework with fos user bundle in order to easily manipulate users.
I've integrated the bundle and everything work fine except that the bundle features don't match my need when it comes to multi users through inheritance !
Is there any trick to implement the multi user inheritance in fos bundle ?
I've tried a lot of different tricks like changing the roles , changing the user model interface, using symfony groups but all of them seemed to be not working !
The thing that will solve [with an ugly way] my problem is to change the value of the discriminator column .
* #ORM\Table(name="fos_user")
* #ORM\InheritanceType("SINGLE_TABLE")
* #ORM\DiscriminatorColumn(name="typeutilisateur", type="string")
* #ORM\DiscriminatorMap({"Parent"="User","admin" =
"Administrateur","association"
="AsoociationsBundle\Entity\Association",
"Demandeurservice"="EldersStoryBundle\Entity\Demandeurservice",
"Formateur"="FormationBundle\Entity\Formateur"
,"Prestataire"="AnnonceEldersCareBundle\Entity\Prestataireservice"})
class User extends BaseUser
{
/**
* #ORM\Id
* #ORM\Column(type="integer")
* #ORM\GeneratedValue(strategy="AUTO")
*/
protected $id;
/**
* #var string
*
* #ORM\Column(name="nom", type="string", length=30, nullable=true)
*/
private $nom;
/**
* #var string
*
* #ORM\Column(name="prenom", type="string", length=30, nullable=true)
*/
private $prenom;
/**
* #var string
*
* #ORM\Column(name="adresse", type="string", length=50)
*/
private $adresse;
/**
* #var string
*
* #ORM\Column(name="telephone", type="integer")
*/
private $telephone;
/**
* #var string
*
* #ORM\Column(name="sexe", type="string", length=30, nullable=true)
*/
private $sexe;
/**
* #var \DateTime
*
* #ORM\Column(name="datecreation", type="datetime")
*/
private $datecreation;
/**
* #var string
*
* #ORM\Column(name="avatar", type="string", length=255)
*/
private $avatar;
/**
* #ORM\ManyToMany(targetEntity="AppBundle\Entity\Group")
* #ORM\JoinTable(name="fos_user_user_group",
* joinColumns={#ORM\JoinColumn(name="user_id", referencedColumnName="id")},
* inverseJoinColumns={#ORM\JoinColumn(name="group_id", referencedColumnName="id")}
* )
*/
protected $groups;
public function __construct()
{
parent::__construct();
}
}
/*This is the sub class*/
<?php
namespace EldersStoryBundle\Entity;
use AppBundle\Entity\User;
use Doctrine\ORM\Mapping as ORM;
/**
* Demandeurservice
*
* #ORM\Table(name="demandeurservice")
* #ORM\Entity(repositoryClass="EldersStoryBundle\
Repository\DemandeurserviceRepository")
*/
class Demandeurservice extends User
{
/**
* #var string
*
* #ORM\Column(name="typemaladie", type="string", length=50)
*/
private $typemaladie;
/**
* #var string
*
* #ORM\Column(name="descriptionmaladie", type="string", length=255)
*/
private $descriptionmaladie;
/**
* #var string
*
* #ORM\Column(name="etatmaladie", type="string", length=255)
*/
private $etatmaladie;
/**
* #var int
*
* #ORM\Column(name="pointelderly", type="integer")
*/
private $pointelderly;
}
Everytime i subscribe i get the row in the table but with a discriminator column value ="parent"
So is there any major way to get this done ? or at least to change the value of the discriminator column ?
Remove the DiscriminatorMap. If you don't create one, Doctrine will generate one automagically. So long as you don't go messing around with names of Entity objects (ie, change Person to Persona, or whatever) then that's your best bet. It's also more dynamic because if/when you add additional types, it will update it for you (when cache is removed).
See here, last bullet point quoted:
If no discriminator map is provided, then the map is generated automatically. The automatically generated discriminator map contains the lowercase short name of each class as key.
Assuming the following two tables, 'user' and 'friends';
'user'
column: id
column: name
'friends'
column: user_id
column: user2_id
Both columns in the friends table correspond to the user table id column.
Now I can simply find users by partial name with the following;
$query='jim';
$result=$em->getRepository('\User\Entity\User')
->createQueryBuilder('u')
->where('u.name like :match')
->setParameter('match', $query.'%')
->setMaxResults(5)
->getQuery()
->getResult();
Now assuming an object of \User\Entity\User userA, how would I do a partial string match for all users that userA is not friends with already ?
EDIT Added the Entity definitions
/**
* User
*
* #ORM\Table(name="user", uniqueConstraints={#ORM\UniqueConstraint(name="name_key", columns={"name"})})
* #ORM\Entity
*/
class User
{
/**
* #var integer
*
* #ORM\Column(name="id", type="bigint", precision=0, scale=0, nullable=false, unique=false)
* #ORM\Id
* #ORM\GeneratedValue(strategy="IDENTITY")
*/
private $id;
/**
* #var string
*
* #ORM\Column(name="name", type="string", length=255, precision=0, scale=0, nullable=false, unique=false)
*/
private $name;
}
/**
* UserFriends
*
* #ORM\Table(name="user_friends", indexes={#ORM\Index(name="user_id_key", columns={"user_id"}), #ORM\Index(name="friend_user_id_key", columns={"friend_user_id"})})
* #ORM\Entity
*/
class UserFriends
{
/**
* #var integer
*
* #ORM\Column(name="id", type="bigint", precision=0, scale=0, nullable=false, unique=false)
* #ORM\Id
* #ORM\GeneratedValue(strategy="IDENTITY")
*/
private $id;
/**
* #var \User\Entity\User
*
* #ORM\ManyToOne(targetEntity="User\Entity\User")
* #ORM\JoinColumns({
* #ORM\JoinColumn(name="friend_user_id", referencedColumnName="id", nullable=true)
* })
*/
private $friendUser;
/**
* #var \User\Entity\User
*
* #ORM\ManyToOne(targetEntity="User\Entity\User")
* #ORM\JoinColumns({
* #ORM\JoinColumn(name="user_id", referencedColumnName="id", nullable=true)
* })
*/
private $user;
}`
We’ll do it in two steps. First, we find out which users they are friends with, then we do a query excluding them.
First, we retrieve an ID list of the user’s friends:
$friendIds = $em->createQuery("
SELECT IDENTITY(uf.user)
FROM User\Entity\UserFriends uf
WHERE uf.user = :id")
->setParameter("id", $userId) // $userId is the ID of the target user
->getResult();
$friendIds = array_map("current", $friendIds); // needed for flattening the array
Now we simply query the user table, excluding the IDs of our friends:
$notMyFriends = $em->createQuery("
SELECT u
FROM User\Entity\User u
WHERE u.id != :ownid
AND WHERE u.id NOT IN (:friends)")
->setParameter("ownid", $userId) // $userId is the ID of the target user
->setParameter("friends", $friendIds)
->getResult();
I’m using plain DQL here, but if you prefer the query builder, you can as well rewrite it to a QB method chain.
(All of the above is from the top of my head, hope it works. If not, please leave a comment and I'll try to fix it.)
By the way, please let me give you a few hints regarding your entity classes:
Entity classes should always be in singular UserFriends → UserFriend.
all of your name="foobar" annotation parameters are redundant, as Doctrine will auto-name your tables, indices and columns.
Same goes for the JoinColumns … you can omit them altogether, unless you want to explicitely change the default behaviour (which you usually don’t).
nullable=true is the default for an xToOne relation, so it can be omitted, too.
nullable=false and unique=false don’t make sense on an ID field. The first is redundant, the second is impossible.
I have this scenario:
The entity MealListDay is one day, which has six meals (entity Meal). Now I use OneToOne relationship. But there is problem, because more days can not have same entity Meal - error: unique constraints. I know, that the entity Meal must be unique in OneToOne relationship, but is there any solution with using only these two tables?
Any idea? Thanks.
Entity MealListDay
/**
* #ORM\Id
* #ORM\Column(type="integer")
* #ORM\GeneratedValue
* #var integer
*/
protected $id;
/**
* #ORM\OneToOne(targetEntity="Meal", cascade={"persist"})
* #ORM\JoinColumn(onDelete="SET NULL")
* #var Meal
*/
protected $elevenses;
/**
* #ORM\OneToOne(targetEntity="Meal", cascade={"persist"})
* #ORM\JoinColumn(onDelete="SET NULL")
* #var Meal
*/
protected $soup;
/**
* #ORM\OneToOne(targetEntity="Meal", cascade={"persist"})
* #ORM\JoinColumn(onDelete="SET NULL")
* #var Meal
*/
protected $mainMeal;
/**
* #ORM\OneToOne(targetEntity="Meal", cascade={"persist"})
* #ORM\JoinColumn(onDelete="SET NULL")
* #var Meal
*/
protected $sideDish;
/**
* #ORM\OneToOne(targetEntity="Meal", cascade={"persist"})
* #ORM\JoinColumn(onDelete="SET NULL")
* #var Meal
*/
protected $drink;
/**
* #ORM\OneToOne(targetEntity="Meal", cascade={"persist"})
* #ORM\JoinColumn(onDelete="SET NULL")
* #var Meal
*/
protected $nosh;
Entity meal:
/**
* #ORM\Id
* #ORM\Column(type="integer")
* #ORM\GeneratedValue
* #var integer
*/
private $id;
/**
* #ORM\Column(type="string", length=150)
*/
protected $name;
/**
* #ORM\Column(type="string", length=20)
*/
protected $type;
/**
* #ORM\Column(type="simple_array", nullable=true)
*/
protected $allergens;
Your mmodel has a first normal form problem.
Try the following:
MealListDay
- id
- dateOffered
MealOffering
- MealListDayID (FK to MealListDay)
- MealId (FK to Meal)
Meal
- id
- name
BTW including allergens in meal will probably result in a 1NF problem also
I must implement relation M:N, there is result.
I know, that property allergens is not in 1NF, but these are only numbers, which links to specific allergen name and description which are defined statically in class.
I am working on a product catalog, and have two entities, PcatSalesItem and PcatCategory with a many-to-many relationship between them. If I delete a category, and there are still sales items associated with it, I want an exception to be thrown, I do NOT want cascading delete. On the RDBMS level (PostgreSQL), in the join table, I have set the foreign keys to "ON DELETE RESTRICT". However, when I delete a category that has sales items, Doctrine does a cascading delete. Nowhere have I specified cascade=remove to Doctrine!
Here are the entities:
/**
* PcatSalesItem
*
* #ORM\Table(name="pcat_sales_item")
* #ORM\Entity
* #Gedmo\Loggable(logEntryClass="Qi\Bss\BaseBundle\Entity\Business\LogEntryBusiness")
*/
class PcatSalesItem
{
/**
* #var integer
*
* #ORM\Column(name="id", type="integer", nullable=false)
* #ORM\Id
* #ORM\GeneratedValue(strategy="SEQUENCE")
* #ORM\SequenceGenerator(sequenceName="pcat_sales_item_id_seq", allocationSize=1, initialValue=1)
*/
private $id;
/**
* #var string
*
* #ORM\Column(name="name", type="string", length=64, nullable=false)
* #Gedmo\Versioned
*/
private $name;
/**
* #var string
*
* #ORM\Column(name="description", type="text", nullable=true)
* #Gedmo\Versioned
*/
private $description;
/**
* #var array $categories
*
* #ORM\ManyToMany(targetEntity="PcatCategory")
* #ORM\JoinTable(name="pcat_category_x_sales_item",
* joinColumns={#ORM\JoinColumn(name="sales_item_id", referencedColumnName="id", onDelete="RESTRICT")},
* inverseJoinColumns={#ORM\JoinColumn(name="category_id", referencedColumnName="id", onDelete="RESTRICT")}
* )
*/
private $categories;
...
}
/**
* PcatCategory
*
* #ORM\Table(name="pcat_category")
* #ORM\Entity
* #Gedmo\Loggable(logEntryClass="Qi\Bss\BaseBundle\Entity\Business\LogEntryBusiness")
*/
class PcatCategory
{
/**
* #var integer
*
* #ORM\Column(name="id", type="integer", nullable=false)
* #ORM\Id
* #ORM\GeneratedValue(strategy="SEQUENCE")
* #ORM\SequenceGenerator(sequenceName="pcat_category_id_seq", allocationSize=1, initialValue=1)
*/
private $id;
/**
* #var string
*
* #ORM\Column(name="name", type="string", length=64, nullable=false)
* #Gedmo\Versioned
*/
private $name;
/**
* #var array $salesItems
*
* #ORM\ManyToMany(targetEntity="PcatSalesItem")
* #ORM\JoinTable(name="pcat_category_x_sales_item",
* joinColumns={#ORM\JoinColumn(name="category_id", referencedColumnName="id", onDelete="RESTRICT")},
* inverseJoinColumns={#ORM\JoinColumn(name="sales_item_id", referencedColumnName="id", onDelete="RESTRICT")}
* )
*/
private $salesItems;
....
}
Here is the code I use to delete a category:
$em = $this->getDoctrine()->getManager();
$cat = $em->getRepository('QiBssBaseBundle:PcatCategory')->find(15);
$em->remove($cat);
$em->flush();
Any help will be greatly appreciated!
Hi I'm created application with table which is one of column is can't be null.
When I'm persisting value with 0 value. The doctrine is saving it to database as null value.
I'm trying to save column sort_id value in my code.
How to save 0 value as 0 integer value?
Here is my code
namespace cms\models\Entities;
use \cms\Doctrine\ORM\Mapping as ORM;
use \cms\Doctrine;
use \cms\models\Entities;
/**
* #Entity
* #Table(name="vkladki")
*/
class Vkladki{
/**
* #Id
* #Column(type="integer")
* #GeneratedValue(strategy="AUTO")
*/
protected $id;
/**
* #Column(type="string", length=255)
*/
protected $title;
/**
* #Column(type="integer")
*/
protected $cat_id;
/**
* #var integer
* #Column(type="integer", nullable=false)
*/
protected $sort_id;
public function setSortId( $sort_id){
$this->sort_id = $sort_id;
}