Get related record one to many relationships Symfony2 - symfony

I want to check if the current user has already a record for the current date.The User entity has many Timerecord and Timerecord has one User. So far,
This two entities resides in two different bundles
Project
UserBundle
TimerecordBundle
controller
$user = $this->container->get('security.context')->getToken()->getUser();
$userr = $user->getUsername();
$alreadyLoggedIn = $em->getRepository('EmployeeBundle:Timerecord')->findAlreadyTimedInToday($userr);
var_dump($alreadyLoggedIn);
die();
Respository
public function findAlreadyTimedInToday($userr)
{
return $this
->createQueryBuilder('t')
->select('u.username')
->from('User u')
->join('u.Timerecord t')
->where('u.username LIKE :currentuser')
->setParameter('currentuser',$userr)
->getQuery()
->getSingleResult()
;
}
I got this exception
Warning: Missing argument 2 for Doctrine\ORM\QueryBuilder::from()
How do you fetch the related user in this case?

The alias for the from part should be given to the second argument.
Change your method to this:
public function findAlreadyTimedInToday($userr)
{
return $this
->createQueryBuilder('t')
->select('u.username')
->from('User', 'u')
->join('u.Timerecord', 't')
->where('u.username LIKE :currentuser')
->setParameter('currentuser', $userr)
->getQuery()
->getSingleResult()
;
}

Related

Symfony - How to use LIKE with COALESCE in a Doctrine request?

I have some trouble with LIKE and COALESCE in a Doctrine request (not 100% sure that the trouble is there).
I would like to search inside a database with a filter that match only if exist, and only with a part of the value (for example find 'abc' with the filter set to 'ab').
This request works fine :
public function findUsers($entreprise, $filtres)
{
$filtre_name = $filtres['name'];
return $this->createQueryBuilder('users')
->where('users.entreprise = :entreprise')
->andWhere('users.name = COALESCE(:filtre_name, users.name)')
->setParameter('entreprise', $entreprise)
->setParameter('filtre_name', $filtre_name)
->orderBy('users.name', 'ASC')
->getQuery()
->getResult();
}
It return all the users of the company "entreprise" where "filtre_name" match (if not null) with "name" in the database. (If "filtre_name" is null, then the where match for all the database thanks to COALESCE).
I would like now to do the same thing but with "LIKE" instead of "=" because for now the name has to match perfectly and I would like a match for "abc" with only "ab" inside the filter for example.
public function findUsers($entreprise, $filtres)
{
$filtre_name = $filtres['name'];
return $this->createQueryBuilder('users')
->where('users.entreprise = :entreprise')
->andWhere('users.name LIKE COALESCE(:filtre_name, users.name)')
->setParameter('entreprise', $entreprise)
->setParameter('filtre_name', '%'.$filtre_name.'%')
->orderBy('users.name', 'ASC')
->getQuery()
->getResult();
}
The result is an error : "Warning: Undefined property: Doctrine\ORM\Query\AST\CoalesceExpression::$type".
I have find a solution. I build my queryBuilder with parameter only if they are not Null. So I remove COALESCE and now I can use LIKE.
public function findUsers($entreprise, $filtres)
{
$filtre_nom = $filtres['nom'];
$filtre_gestionnaire = $filtres['gestionnaire'];
$qb = $this ->createQueryBuilder('users');
$qb ->where('users.entreprise = :entreprise')
->setParameter('entreprise', $entreprise);
if ($filtre_nom != Null) {
$qb ->andWhere('users.nom LIKE :filtre_nom')
->setParameter('filtre_nom', '%'.$filtre_nom.'%');
}
if ($filtre_gestionnaire != Null) {
$qb ->andWhere('users.gestionnaire LIKE :filtre_gestionnaire')
->setParameter('filtre_gestionnaire', '%'.$filtre_gestionnaire.'%');
}
$qb->addorderBy('users.nom', 'ASC');
return $qb ->getQuery()
->getResult();
}

ParamConverter: inject curent user in Repository

In a view, I want to display linked values, but all of the linked values can't be displayed because they depends to the user access.
To do that I just need to do a leftJoin with a ->where('user', $user). The question is... how can I inject the current user in the Repository from the ParamConverter ?
Assuming you are using Doctrine, this should work;
In your controller;
$objRepo = $this->getDoctrine()->getManager()->getRepository('AppBundle:Objects');
$files = $this->objRepo->getAllForUserId($this->getUser()->getId());
And in your repo file;
public function getAllForUserId($user_id, $limit=100)
{
if (null === $user_id) {
throw new ORMInvalidArgumentException('User id not set');
}
$queryBuilder = $this->createQueryBuilder('obj');
$queryBuilder->select(array('obj', 'usr'))
->innerJoin('obj.users', 'usr')
->where('usr.id = :user_id')
->setParameter(':user_id', $user_id)
->orderBy('file.created', Criteria::DESC);
$query = $queryBuilder->getQuery();
return $query->getResult();
}

How to sum the contents of a document field with symfony query builder?

I am just trying to get the total value of one of the fields of my documents but it's not working. What am I missing?
#ProductRepository
public function countTotalValue()
{
return $this->createQueryBuilder('a')
->select('SUM(a.price)')
->getQuery()
->getSingleScalarResult()
;
}
I discovered it!
public function countTotalValue()
{
$array = $this->createQueryBuilder()
->select('price')
->hydrate(false)
->getQuery()
->execute()
->toArray()
;
$array = array_column($array, 'price');
return (array_sum($array));
}
It was returning a complex array, I had to stripe it before make the sum.

how to access annotation of an property(class,mappedBy,inversedBy)

Good morning,
Is it exist an function where I pass an entity and the propertyName and return me the mappedBy,inversedBy and absoluteClassName of an Entity.
The goal is to use the __call to create automatic getteur/setteur and addFucntion bidirectionnal.
I don't want to use generates Entities I want all getteur,setteur and add Function use __call.
But i can"t do an addBirectionnal if i don't know if the relation is many to many or one to many and if i don't know the name of the mappedBy.
my code:
public function __get($p){
return $this->$p;
}
public function __set($p,$v){
$this->$p = $v;
return $this;
}
public function __call($name,$arguments){
if(substr($name,1,3)=='et')
$name2 = substr(3);
if($name[0] == 'g'){
return $this->$name2;
}else{//substr($name,0,1) == 's'
$this->$name2 = $arguments[0];
/*for a one to one*/
/*$mappedByName= getmappedByOrInversedBy(get_class($name),$name2);
if($mappedByName){
$this->$name->$mappedByName = $this;/
}*/
return $this;
}
}
}
I need getmappedByOrInversedBy, thanks.
edit: I try this
public function test(){
$str = "AppBundle\Entity\Group";
$mapping = new \Doctrine\ORM\Mapping\ClassMetadataInfo($str);
$d = $mapping->getAssociationMappedByTargetField('trad');
var_dump($d);
return $this->render('default/index.html.twig', array(
'base_dir' => realpath($this->getParameter('kernel.root_dir').'/..'),
));
}
class Group
{
...
/**
* #ORM\OneToOne(targetEntity="Traduction",inversedBy="grp")
*/
protected $trad;
}
Result : Undefined index: trad
The ClassMetadataInfo is what you are looking for.
Creates an instance with the entityName :
$mapping = new \Doctrine\ORM\Mapping\ClassMetadataInfo($entityNamespaceOrAlias);
Then, get the informations you want :
Get all association names: $mapping->getAssociationNames();
Get the join column of an association:
$mapping->getSingleAssociationJoinColumnName($fieldName);
Get the mappedBy column of an association:
$mapping->getAssociationMappedByTargetField($fieldName);
...
Look at the class to know which method you can access.
Hopes it's what you expect.
EDIT
As you can access the EntityManager (i.e. from a controller), use :
$em = $this->getDoctrine()->getManager();
$metadata = $em->getClassMetadata('AppBundle:Group');
To be sure there is no problem with your entity namespace, try :
print $metadata->getTableName();
To retrieve the associations of the entity, use :
$metadata->getAssociationNames();
And to get the mapping informations of an existing association, use :
$metadata->getAssociationMapping($fieldName);
And to get all the association mappings of your entity, use:
$metadata->getAssociationMappings();

unique slugs with multi entities in symfony2

I have a small symfony2 application where a user can create pages. Each page should be accessible via the route /{user_slug}/{page_slug}. I have the entities user and page and I use the sluggable behavior for both entities. In order to find the correct page the combination of user_slug and page_slug has to be unique.
What is the best way to check that the combination of user_slug and page_slug is uniqe?
Try this in your prepository:
public function findByUsernameAndSlug($username, $slug)
{
$em = $this->getEntityManager();
$query = $em->createQuery("
SELECT g
FROM Acme\PagesBundle\Entity\Page p
JOIN p.owner u
WHERE u.username = :username
AND p.slug = :slug
")
->setParameter('username', $username)
->setParameter('slug', $slug);
foreach ($query->getResult() as $goal) {
return $goal;
}
return null;
}
Before you persist the entity in your service-layer check whether given combination of user and page slug are unique, if not modify the page slug (append -2 or something like that) or throw an exception:
public function persistPage(Page $page) {
$userSlug = $page->getUser()->getSlug();
$pageSlug = $page->getSlug();
if ($this->pagesRepository->findOneBySlugs($userSlug, $pageSlug) != null) {
// given combination already exists
throw new NonUniqueNameException(..);
// or modify the slug
$page->setSlug($page->getSlug() . '-2');
return $this->persistPage($page);
}
return $this->em->persist($page);
}
// PagesRepository::findOneBySlugs($userSlug, $pageSlug)
public function findOneBySlugs($userSlug, $pageSlug) {
$query = $this->em->createQueryBuilder('p')
->addSelect('u')
->join('p.user', 'u')
->where('p.slug = :pageSlug')
->where('u.slug = :userSlug;)
->getQuery();
$query->setParameters(combine('userSlug', 'pageSlug'));
return $query->getSingleResult();
}

Resources