SQL error when using DQL with symfony - sql

I am using symfony framework, and when I tried this DQL methode to recover username for the Fos_user table generated by the FOSUser bundle
namespace UserBundle\Repository;
use Doctrine\ORM\EntityRepository;
class UserRepository extends EntityRepository
{
public function findEmailDQL($email)
{
$query=$this->getEntityManager()
->createQuery("SELECT u.username
FROM UserBundle:User u
WHERE u.id = $email");
return $query->getResult();
}
}
with the controller function
public function findByEmailJsonAction($email)
{
$users=$this->getDoctrine()->getManager()
->getRepository('UserBundle:User')
->findEmailDQL($email);
$serializer = new Serializer([new ObjectNormalizer()]);
$formatted =$serializer->normalize($users);
return new JsonResponse($formatted);
}
I keep getting this error when I try looking for the user with id 127:
An exception occurred while executing 'SELECT u0_.username AS username_0 FROM user u0_ WHERE u0_.id = 127':
SQLSTATE[42S22]: Column not found: 1054 Champ 'u0_.username' inconnu dans field list

:-)
Try this !
$users = $this->getDoctrine()->getRepository("UserBundle:User")->findBy(array("email" => $email));
Or for just one:
$user = $this->getDoctrine()->getRepository("UserBundle:User")->findOneBy(array("email" => $email));
Good luck ! :-)

Symfony EntityRepository create queryBuilder:
class UserRepository extends EntityRepository
{
public function findEmailDQL($email)
{
return $this->createQueryBuilder('u')
->select('u.username')
->where('u.your_stuff_field = :stuff')
->setParameter('stuff' => $email)
->getQuery()
->getSingleResult();
}
}

Related

Symfony 5 use getDoctrine() in another Controller

I try to call "class CltvController" from another class like this :
class StatLtvcController extends AbstractController
{
$cltv_temp = new CltvController();
return $this->render('admin/statltvc.html.twig', [ 'cltv_temp' => $cltv_temp->cltv(), ]);
}
but this class :
namespace App\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use App\Entity\Game;
use App\Entity\Adventure;
use Symfony\Component\Routing\Annotation\Route;
class CltvController extends AbstractController
{
public function cltv(): float{
$periodh = '2021-06-01'; // $request->request->get('')
$periodi = '2021-07-31'; // $request->request->get('')
$em = $this->getDoctrine()->getManager();
$con = $em->getRepository(Game::class);
$con3 = $em->getRepository(Adventure::class);
$ncnt[] = $con->findByCountncn($periodh,$periodi);
$nadvt[] = $con3->findByCountadv($periodh,$periodi);
return $nadvt[0][0][1]/$ncnt[0][0][1];
}
}
is returning this error :
Call to a member function has() on null
Error
in G:\Mes_TPs\TP_Symfony_PHP\Quaestyo\vendor\symfony\framework-bundle\Controller \AbstractController.php (line 345)
*
* #throws \LogicException If DoctrineBundle is not available
*/
protected function getDoctrine(): ManagerRegistry
{
if (!$this->container->has('doctrine')) {
throw new \LogicException('The DoctrineBundle is not registered in your application. Try running "composer require symfony/orm-pack".');
}
return $this->container->get('doctrine');
}
I don't understand why $this->getDoctrine is returning an error?
Try to add this bloc over CltvController class:
/**
* #method getDoctrine()
*/
class CltvController extends AbstractController {
• If that didn't work, can you tell me the exact version of php & symfony of your project please?
Thanks for your answer. It's the same error message with your solution.Actually, Symfony is calling getDoctrine() in the class StatLtvcController. (i didn't put all because code was too long). How could i call getdoctrine() in the class CltvController ?
I use last versions : PHP 7.4.9 and Symfony 5.2.14

Doctrine ORM create method phpspec test failure

I try to write, at first glance, it would seem a trivial test for my repository's "update" method:
<?php
declare(strict_types=1);
namespace Paneric\Authorization\ORM\Repository;
use Doctrine\ORM\EntityManagerInterface;
use Doctrine\ORM\ORMException;
use Paneric\Authorization\DTO\FieldDTO;
use Paneric\Authorization\ORM\Entity\Field;
use Doctrine\ORM\EntityRepository;
use Paneric\Authorization\Interfaces\FieldRepositoryInterface;
class FieldRepository extends EntityRepository implements FieldRepositoryInterface
{
const ENTITY_CLASS = Field::class;
public function __construct(EntityManagerInterface $_em)
{
parent::__construct($_em, $_em->getClassMetadata(self::ENTITY_CLASS));
}
...
public function update(int $fieldId, FieldDTO $fieldDTO): void
{
try {
$field = $this->find($fieldId);
$field->transfer($fieldDTO);
$this->_em->flush();
} catch (ORMException $e) {
echo $e->getMessage();
}
}
...
}
with a spec method:
<?php
namespace spec\Paneric\Authorization\ORM\Repository;
use Doctrine\ORM\EntityManagerInterface;
use Doctrine\ORM\Mapping\ClassMetadata;
use Doctrine\ORM\QueryBuilder;
use Paneric\Authorization\DTO\FieldDTO;
use Paneric\Authorization\ORM\Entity\Field;
use Paneric\Authorization\ORM\Repository\FieldRepository;
use Doctrine\ORM\AbstractQuery;
use PhpSpec\ObjectBehavior;
use Prophecy\Argument;
class FieldRepositorySpec extends ObjectBehavior
{
public function let(EntityManagerInterface $_em, ClassMetadata $classMetadata)
{
$_em->getClassMetadata(Field::class)->willReturn($classMetadata);
$this->beConstructedWith($_em);
}
...
public function it_updates(Field $field, FieldDTO $fieldDTO, EntityManagerInterface $_em)
{
$fieldId = 1;
$field = $this->find($fieldId);
$field->transfer($fieldDTO)->shouldBeCalled();
$_em->flush()->shouldBeCalled();
$this->update($fieldId, $fieldDTO);
}
...
}
and receive the following error:
Unexpected method call on Double\EntityManagerInterface\EntityManagerInterface\P1:
- find(
null,
1,
null,
null
)
expected calls were:
- getClassMetadata(
exact("Paneric\Authorization\ORM\Entity\Field")
)
- find(
exact("Paneric\Authorization\ORM\Entity\Field"),
exact(1)
)
- flush(
)
Apparently issue is related to the call:
...
$field = $this->find($fieldId);
...
Although the second remark related to getClassMetadata, looks strange, considering the fact that my spec let method:
public function let(EntityManagerInterface $_em, ClassMetadata $classMetadata)
{
$_em->getClassMetadata(Field::class)->willReturn($classMetadata);
$this->beConstructedWith($_em);
}
does its job in case of other spec tests.
Can anyone help me to solve this issue ? Thx in advance.
In my repository's "update" metod, line:
$field = $this->find($fieldId);
has to be replaced by:
$field = $this->_em->find(Field::class, $fieldId);
so the complete spec test looks like:
public function it_updates(Field $field, FieldDTO $fieldDTO, EntityManagerInterface $_em)
{
$fieldId = 1;
$_em->find(Field::class, $fieldId)->willReturn($field);
$field->transfer($fieldDTO)->shouldBeCalled();
$_em->flush()->shouldBeCalled();
$this->update($fieldId, $fieldDTO);
}

Symfony 4: Fetching user from DB ind custom user provider returns "Bad Credentials"

I am building an API based on Symfony 4.
In my custom user provider I dump the users email and the user data from database.
The email is shown but the second dump does not appear.
While fetching the user data it returns "Bad Credentials".
Here is my user provider:
<?php
// src/Security/User/WebserviceUserProvider.php
namespace App\Security\User;
use Symfony\Component\Security\Core\User\UserProviderInterface;
use Symfony\Component\Security\Core\User\UserInterface;
use Symfony\Component\Security\Core\Exception\UsernameNotFoundException;
use Symfony\Component\Security\Core\Exception\UnsupportedUserException;
class WebserviceUserProvider implements UserProviderInterface
{
private $doctrine;
public function __construct (\Doctrine\Bundle\DoctrineBundle\Registry $doctrine)
{
$this->doctrine = $doctrine;
}
public function loadUserByUsername($email)
{
var_dump($email);
$userData = $this->doctrine->getManager()
->createQueryBuilder('SELECT u FROM users u WHERE u.email = :email')
->setParameter('email', $email)
->getQuery()
->getOneOrNullResult();
var_dump($userData);exit;
// pretend it returns an array on success, false if there is no user
if ($userData) {
$username = $userData['email'];
$password = $userData['password'];
$salt = $userData['salt'];
$roles = $userData['roles'];
// ...
return new WebserviceUser($username, $password, $salt, $roles);
}
throw new UsernameNotFoundException(
sprintf('Username "%s" does not exist.', $username)
);
}
public function refreshUser(UserInterface $user)
{
if (!$user instanceof WebserviceUser) {
throw new UnsupportedUserException(
sprintf('Instances of "%s" are not supported.', get_class($user))
);
}
return $this->loadUserByUsername($user->getUsername());
}
public function supportsClass($class)
{
return WebserviceUser::class === $class;
}
}
If I send my json login data it returns the following:
string(13) "test#test.com" {"code":401,"message":"Bad credentials"}
Does anyone know this problem?

How to execute query in phalcon model

iam using phalcon, I tried to execute query from controller, query run my model
<?php
use Phalcon\Mvc\Model;
use Phalcon\Mvc\Model\Query;
class CakupanBu extends Phalcon\Mvc\Model
{
public static function getJenisBU()
{
header("Access-Control-Allow-Origin: *");
header('Content-type:application/json;charset=utf-8');
$data = array();
$query = new Query(
'SELECT id_jenis_bu,count(jumlah_bu) as jumlah FROM CakupanBu group by id_jenis_bu',
$this->getDI()
);
// Execute the query returning a result if any
$jbus = $query->execute();
foreach ($jbus as $jbu) {
$data[] = array(
'id_jenis' => $jbu->id_jenis_bu,
'jumlah' => $jbu->jumlah,
);
}
return json_encode($data);
}
}
But sadly this is not working, and I ended up with an error.
<b>Fatal error</b>: Uncaught Error: Using $this when not in object context in 'CakupanBU.php:14'
from controller i call :
$jbus=CakupanBU::getJenisBU();
Could anyone give me solution? thanks you
Your function is static, so there is no $this.
To get the DI, you would replace your $this->getDI() with \Phalcon\DI::getDefault()

Why is my User Login no longer working after upgrading to Symfony3

I came along a strange Problem with Symfony 3.
Under Symfony 2 everyhting worked out of the Box (Login).
But under Symfony 3 it doesn't validate at all.
The Doctrine Layer is not Loading my User Object nor the Repository.
Whats going on?
UserProviderInterface was changed to UserLoaderInterface in 2.8 (see doc)
class UserRepository extends EntityRepository implements
UserProviderInterface
class UserRepository extends EntityRepository
implements UserLoaderInterface
This wil fix the problem, you can also delete these functions:
public function refreshUser(UserInterface $user)
public function supportsClass($class)
Ok, short update.
I was able to fix this and would like to share what happened.
After Debuging the complete Login Prozess I stumbled accross the main cause for not beeing able to login.
<?php
// src/AppBundle/Entity/UserRepository.php
namespace AppBundle\Entity;
use Symfony\Component\Security\Core\User\UserInterface;
use Symfony\Component\Security\Core\User\UserProviderInterface;
use Symfony\Component\Security\Core\Exception\UsernameNotFoundException;
use Symfony\Component\Security\Core\Exception\UnsupportedUserException;
use Doctrine\ORM\EntityRepository;
class UserRepository extends EntityRepository implements UserProviderInterface
{
public function loadUserByUsername($username)
{
$user = $this->createQueryBuilder('u')
->where('u.username = :username OR u.email = :email')
->setParameter('username', $username)
->setParameter('email', $username)
->getQuery()
->getOneOrNullResult();
if (null === $user) {
$message = sprintf(
'Unable to find an active admin AppBundle:User object identified by "%s".',
$username
);
throw new UsernameNotFoundException($message);
}
return $user;
}
public function refreshUser(UserInterface $user)
{
$class = get_class($user);
if (!$this->supportsClass($class)) {
throw new UnsupportedUserException(
sprintf(
'Instances of "%s" are not supported.',
$class
)
);
}
return $this->find($user->getId());
}
public function supportsClass($class)
{
return $this->getEntityName() === $class
|| is_subclass_of($class, $this->getEntityName());
}
}
Ok,
this Repository Query Class is actually the reason why it is not working.
After Debuging and Testing I came Along this Code Block in the Class:
Symfony\Bridge\Doctrine\Security\User
/**
* {#inheritdoc}
*/
public function loadUserByUsername($username)
{
if (null !== $this->property) {
$user = $this->repository->findOneBy(array($this->property => $username));
} else {
if (!$this->repository instanceof UserLoaderInterface) {
throw new \InvalidArgumentException(sprintf('The Doctrine repository "%s" must implement Symfony\Bridge\Doctrine\Security\User\UserLoaderInterface.', get_class($this->repository)));
}
$user = $this->repository->loadUserByUsername($username);
}
if (null === $user) {
throw new UsernameNotFoundException(sprintf('User "%s" not found.', $username));
}
return $user;
}
It states that the Repository Class must be an instance of UserLoaderInterface.
But the Documentation from
http://symfony.com/doc/current/cookbook/security/entity_provider.html
states it is an Instance of UserProviderInterface.
so the Login fails as it is not the right Interface implemented.
The Documentation (Cookbook) has an old Information in it, or the Symfony Team just simply forgot about it. ^^(can happen)
Hope this helps someone ^^
For me the issue was that the isEqualTo method of the EquatableInterface (on my User entity) was returning false when it should have been returning true.