I'm trying to convert this MySql query
SELECT appcs_training.name, appcs_training.id FROM appcs_training
WHERE appcs_training.id
NOT IN (SELECT training_id FROM appcs_user_purchased_trainings WHERE user_id = 54)
into a queryBuilder but I am getting the following error over and over again...
I would appreciate your help to solve this.
[Semantical Error] line 0, col 57 near 'training FROM': Error: Invalid PathExpression. Must be a StateFieldPathExpression.
And this is my code:
public function findNonPurchasedTrainingsByUserId($userId)
{
$expr = $this->em->getExpressionBuilder();
return $this->em->createQueryBuilder()
->select('t')
->from('App:Training', 't')
->where($expr->notIn(
't.id',
$this->em->createQueryBuilder()
->select('ut.training')
->from('App:UserTraining', 'ut')
->where('ut.user = :userId')
->setParameter('userId', $userId)
->getDQL()
))
->getQuery()
->getResult();
}
Finally, setParameter wasn't valid. This is the only way I made it work
public function findNonPurchasedTrainingsByUserId(int $userId)
{
$expr = $this->getEntityManager()->getExpressionBuilder();
$subQuery = $this->em->createQueryBuilder()
->select('tr.id')
->from('App:UserTraining', 'ut')
->leftJoin('App:Training', 'tr', Join::WITH, $expr->eq('ut.training', 'tr.id'))
->where($expr->eq('ut.user', $userId))
->getDQL()
;
$query = $this->em->createQueryBuilder();
$query->Select('t')
->from('App:Training', 't')
->where($query->expr()->notIn('t.id', $subQuery))
->andWhere($query->expr()->eq('t.isActive', true))
->setMaxResults(8)
;
return $query->getQuery()->getResult();
}
Related
I am working in Symfony - When I am performing an action to delete a user I am receiving the following error messages:
[Semantical Error] line 0, col 7 near 'WHERE u.id =': Error: Class 'WHERE' is not defined.
500 Internal Server Error - QueryException
1 linked Exception:
QueryException »
1/2 QueryException: DELETE WHERE u.id = :id
2/2 QueryException: [Semantical Error] line 0, col 7 near 'WHERE u.id =': Error: Class 'WHERE' is not defined.
Admin Controller
/**
* #Route("/admin/user/delete/{id}", name="admin_user_delete")
* #Template
*/
public function deleteAction($id)
{
$dispatcher = $this->container->get('event_dispatcher');
$this->get('users')->delete($id);
// create the user event and dispatch it
$event = new UserEvent($id);
$dispatcher->dispatch(UserEvents::USER_DELETED, $event);
$this->get('session')->getFlashBag()->add('notice-success', 'User deleted successfully.');
return $this->redirect($this->generateUrl('admin_user_list'));
}
User.php Service
public function delete($id)
{
$this->repository->delete($id);
}
User Repository
public function delete($id)
{
$qb = $this->getEntityManager()->createQueryBuilder('u');
$qb->delete()
->andWhere($qb->expr()->eq('u.id', ':id'))
->setParameter(':id', $id)
->getQuery()
->getResult();
}
Method to delete a user with the query builder
public function delete($id)
{
$qb = $this->getEntityManager()->createQueryBuilder();
return $qb->delete('Bundle:User', 'u')
->where('u.id = :id'))
->setParameter('id', $id)
->getQuery()
->getResult();
}
How to delete a user using the built in ORM
public function delete($id) {
// get access to the entity manager
$em = $this->getEntityManager();
// get the user from the repository by id
// previous version, slightly slower as it executes a query
// $user = $em->getRepository('Bundle:User')->find($id);
// Cerads method I just found out about myself, even better version!
// this doesn't execute a query but gets a reference to the user object
// and sets the id
$user = $em->getReference('Bundle:User', $id);
// use built in methods to delete the user
$em->remove($user);
// update the database with the change
$em->flush();
}
As Jared Farrish said above, you don't need the colon in the setParameter call.
Should be:
->setParameter('id', $id)
[Semantical Error] line 0, col 75 near 'sesion sesion':
Error: Invalid PathExpression. Must be a StateFieldPathExpression.
TopicsRepository class code:
class TopicsRepository extends EntityRepository {
public function findAllTopics() {
return $this->getEntityManager()
->createQueryBuilder()
->select('t.id,'
. 't.name,'
. 't.name stream_id,'
. 't.name admin_id,'
. 't.name instructor_id,'
. 't.sesion sesion'
)
->from('FeedbackBundle:Topics', 't')
->innerJoin('FeedbackBundle:Streams', 'sr', 'WITH', 't.stream = sr.id')
->innerJoin('FeedbackBundle:Sessions', 'ss', 'WITH', 't.session = ss.id')
->innerJoin('FeedbackBundle:Adminlogin', 'ad', 'WITH', 't.admin = ad.id')
->innerJoin('FeedbackBundle:Instructors', 'i', 'WITH', 't.admin = i.id')
->orderBy('t.id')
->getQuery()
->getResult();
}
}
public function viewTopicAction(Request $request) {
$viewtopic = $this->getDoctrine()
->getRepository('FeedbackBundle:Topics')
->findAllTopics();
return $this->render('FeedbackBundle:Topic:view_topic.html.php', array('viewtopics' => $viewtopics));
}
Must be a StateFieldPathExpression. What is the solution? i can not get any idea.
I wrote a function in BudgetRepository that is called when inserting new data into Budget table. The function is:
public function addBudgetToClient($clientId, $budgetId)
{
return $this->createQueryBuilder('b')
->update('PanelBundle:Client', 'c')
->set('c.budget', $budgetId)
->where('c.id = ' . $clientId)
->getQuery()
->execute();
}
And the BudgetController does this:
public function addAction(Request $request)
{
$form = $this->createForm(new BudgetType());
$manager = $this->getDoctrine()->getManager();
$Budget = $manager->getRepository('PanelBundle:Budget');
$Client = $manager->getRepository('PanelBundle:Client');
if ($request->getMethod() == 'POST') {
$form->handleRequest($request);
if ($form->isValid()) {
$manager->persist($form->getData());
$manager->flush();
// Here's the method:
$Budget->addBudgetToClient($form['client_id']->getData()->getId(), $Budget->getLastId());
//
$this->addFlash('success', 'Novo orçamento adicionado');
return $this->redirect($this->generateUrl('panel_budgets'));
}
}
return $this->render('PanelBundle:Budget:add.html.twig', array(
'clients' => $Client->findAll(),
'form' => $form->createView()
));
}
I tested both outputs, the getLastId is also a custom function I wrote to retrieve the biggest ID from Budget, and the $form['client_id']->getData()->getId() also retrieves the Client id. I guess Symfony2 automatically does something because Budget and Client are related, and even saving the Client id, in the database shows the Client name, I don't understand how actually.
The issue here are these errors:
[Semantical Error] line 0, col 34 near 'budget = 4 WHERE': Error: Invalid PathExpression. StateFieldPathExpression or SingleValuedAssociationField expected.
[2/2] QueryException: [Semantical Error] line 0, col 34 near 'budget = 4 WHERE': Error: Invalid PathExpression. StateFieldPathExpression or SingleValuedAssociationField expected. +
[1/2] QueryException: UPDATE PanelBundle:Client c SET c.budget = 4 WHERE c.id = 1 +
I found many problems about this exception but they haven't had it with update function, only select.
You should not build an update query for this case using a queryBuilder. Use OOP approach to update your entities.
if ($form->isValid()) {
$budgetEntity = $form->getData();
$manager->persist($budgetEntity);
$clientEntity = $Budget->find($form['client_id']->getData()->getId());
$clientEntity->setBudget($budgetEntity);
$manager->flush();
$this->addFlash('success', 'Novo orçamento adicionado');
return $this->redirect($this->generateUrl('panel_budgets'));
}
I'm using symfony 2.2.3 and sonata admin in dev-master.
I would like a custom field to show users from a specific group.
I've not found how to make the relation with Sonata User entity and Sonata Group entity.
The doctrine schema create 3 tables : fos_user_user, fos_user_group and the relation table fos_user_user_group.
I've a form with a field like that in my Admin class :
->add('coach', 'entity', array(
'class' => 'ApplicationSonataUserBundle:User',
'empty_value' => 'Choisissez un coach',
'property' => 'username',
'query_builder' => function(\Application\Sonata\UserBundle\Entity\UserRepository $er) {
return $er->getCoachs();
},
))
And my function getCoachs() in UserRepository:
public function getCoachs()
{
$em = $this->getEntityManager();
$qb = $em->createQueryBuilder(array('u', 'g'))
->select('u.username, g.id')
->from('ApplicationSonataUserBundle:User', 'u')
->innerJoin('ApplicationSonataUserBundle:Group', 'g', 'WITH','g.id = u.group_id')
->where('g.id = :id')
->setParameter('id', 1);
return $qb;
}
I know that the query doesn't work because the innerJoin isn't correct.
My user entity and group entity just extends BaseUser and GroupUser with an id.
Someone know the right query ?
Thank you.
EDIT :
Ok i've found the solution for the query :
public function getCoachs()
{
$em = $this->getEntityManager();
$qb = $em->createQueryBuilder('u')
->select('u.username')
->from('ApplicationSonataUserBundle:User', 'u')
->innerJoin('u.groups', 'g')
->where('g = :id')
->setParameter('id', 1);
return $qb;
}
However, i've this error :
Expected argument of type "object or array", "string" given
I don't understand because I return my function getCoachs() which return a query builder...
No idea ?
Ok I've found the solution !
My query is :
public function getCoachs()
{
$em = $this->getEntityManager();
$qb = $em->createQueryBuilder('u')
->select('u') // and not u.username
->from('ApplicationSonataUserBundle:User', 'u')
->innerJoin('u.groups', 'g')
->where('g = :id')
->setParameter('id', 1);
return $qb;
}
In fact, I returned values of a specific column (username) but you have to return the object User.
Hi
I've got the following query but it doesn't seem to work.
$q = $this->em->createQueryBuilder()
->update('models\User', 'u')
->set('u.username', $username)
->set('u.email', $email)
->where('u.id = ?1')
->setParameter(1, $editId)
->getQuery();
$p = $q->execute();
This returns the following error message:
Fatal error: Uncaught exception
'Doctrine\ORM\Query\QueryException'
with message '[Semantical Error] line
0, col 38 near 'testusername WHERE':
Error: 'testusername' is not defined.'
in ...
I would be glad of any help
I think you need to use ->set() It's much safer to make all your values parameters:
$queryBuilder = $this->em->createQueryBuilder();
$query = $queryBuilder->update('models\User', 'u')
->set('u.username', ':userName')
->set('u.email', ':email')
->where('u.id = :editId')
->setParameter('userName', $userName)
->setParameter('email', $email)
->setParameter('editId', $editId)
->getQuery();
$result = $query->execute();
Let's say there is an administrator dashboard where users are listed with their id printed as a data attribute so it can be retrieved at some point via JavaScript.
An update could be executed this way …
class UserRepository extends \Doctrine\ORM\EntityRepository
{
public function updateUserStatus($userId, $newStatus)
{
return $this->createQueryBuilder('u')
->update()
->set('u.isActive', '?1')
->setParameter(1, $qb->expr()->literal($newStatus))
->where('u.id = ?2')
->setParameter(2, $qb->expr()->literal($userId))
->getQuery()
->getSingleScalarResult()
;
}
AJAX action handling:
# Post datas may be:
# handled with a specific custom formType — OR — retrieved from request object
$userId = (int)$request->request->get('userId');
$newStatus = (int)$request->request->get('newStatus');
$em = $this->getDoctrine()->getManager();
$r = $em->getRepository('NAMESPACE\User')
->updateUserStatus($userId, $newStatus);
if ( !empty($r) ){
# Row updated
}
Working example using Doctrine 2.5 (on top of Symfony3).
With a small change, it worked fine for me
$qb=$this->dm->createQueryBuilder('AppBundle:CSSDInstrument')
->update()
->field('status')->set($status)
->field('id')->equals($instrumentId)
->getQuery()
->execute();