Is possible to make a request by one filed or another using the orm on symfony
$user_test = $em->getRepository("AppBundle:UserTest")->findOneBy([
'hash' => $data->user_data->hash,
'code' => $data->user_data->hash],
);
to get something like WHERE hash = 'foo' OR code = 'foo'
you have to define the method in the entity UserTest repository
// UserTestRepository.php
public function getUserTestByHashOrCode($hash, $code){
return $this->createQueryBuilder('u')
->where('hash = :hash')
->orWhere('code = :code')
->setParameter('hash', $hash)
->setParameter('code', $code)
->getQuery()
->getOneOrNullResult();
and then
$user_test = $em->getRepository("AppBundle:UserTest")->getUserTestByHashOrCode($data->user_data->hash, $data->user_data->hash);
Related
A method from my MyClass class I'd like to test looks like this:
public function needs()
{
$domains = $this->em->getRepository(WebDomain::class)->findBy(array(
'client' => $this->client
));
$hosting = $this->em->getRepository(WebHosting::class)->findBy(array(
'client' => $this->client
));
if($domains !== null && $hosting !== null){
return true;
}
return false;
}
Looking at the documentation of Symfony I create a test like this:
public function testNeeds()
{
$em = $this->createMock(ObjectManager::class);
$client = new Client();
/**
* Add WebHosting to Client
*/
$webHosting = new WebHosting();
$webHosting->setClient($client);
/**
* Create a new WebDomain for Client/WebHosting
*/
$webDomain = new WebDomain();
$webDomain->setClient($client);
$webDomain->setWebHosting($webHosting);
I know how to create a mocked repository (the needed $domains for example):
$domains = $this->createMock(ObjectRepository::class);
$domains->expects($this->any())
->method('findBy')
->willReturn($client->getWebDomain());
$em->expects($this->any())
->method('getRepository')
->willReturn($domains);
$myClass = new MyClass($client, $em);
So from my understanding, this creates a mock that whenever the method findBy is called, return the $domains, but what do I have to add in order to return the needed $hosting?
I suspect it has something to do with the $this->any(), I assume I have to narrow it down to expects(WebDomain::class) (which does not work ofc).
Since I am fairly new to UnitTests in Symfony (and in general) pointing me to the right manual might help as well. Thank you!
In you case you should return different Repository based on argument passed to getRepository method. Something like:
$emMock
->method('getRepository')
->will($this->returnValueMap([
[WebDomain::class, $webDomainRepositoryMock),
[WebHosting::class, $webHostingRepositoryMock)
]));
Note: remember to configure findBy for both repositories.
I am using symfony and am inside the controller trying to return a set of records by using a range (rangeUpper, rangeLower).
I am passing the parameters in the request object fine. But when going to route in the controller and trying to access the repository class I am at a loss. My repository looks like;
public function findAllByParams (Request $request)
{
$criteria = $request->query->get('uniflytebundle_material-stock_select');
$criteria = ($request->get('materialId') == 0 ? [] : ['materialId' => $request->get('materialId')]);
$criteria = array_merge(($request->get('gaugeId') == 0 ? [] : ['gaugeId' => $request->get('gaugeId')]), $criteria);
$criteria = array_merge(($request->get('rangeUpper') == 0 ? [] : ['rangeUpper' => $request->get('rangeUpper')]), $criteria);
$criteria = array_merge(($request->get('rangeLower') == 0 ? [] : ['rangeLower' => $request->get('rangeLower')]), $criteria);
$criteria = array_filter($criteria);
$query = $this->createQueryBuilder('ms');
if (!empty($criteria)) {
if (!empty($criteria['materialId']) && !empty($criteria['gaugeId']) && !empty($criteria['rangeUpper']) && !empty($criteria['rangeLower'])) {
$query
->where('ms.material = :materialId')
->andWhere('ms.gauge = :gaugeId')
->andWhere('ms.widthDecimal <= :upperIdentifier')
->andWhere('ms.widthDecimal >= :lowerIdentifier')
->setParameter('materialId', $criteria['materialId'])
->setParameter('gaugeId', $criteria['gaugeId'])
->setParameter('upperIdentifier', $criteria['rangeUpper'])
->setParameter('lowerIdentifier', $criteria['rangeLower'])
;
}
}
$query->orderBy('ms.widthDecimal', 'DESC');
return $query->getQuery()->getResult();
}
My current controller looks like
public function selectStripWidthAction (Request $request)
{
$em = $this->getDoctrine()->getManager();
$materialId = $request->get('materialId');
$gaugeId = $request->get('gaugeId');
$materialStocks = $em->getRepository('UniflyteBundle:MaterialStock')->findAllByParams($request);
return $this->render('materialstock/dialog/select.html.twig', [
'MaterialStocks' => $materialStocks,
]);
}
In the Repository I have the query setup to accept and query by the Range. How do I pass the request object and retrieve the result set from the Repository? FindAllByParams call in the controller is not working.
Undefined method 'findAllByParams'. The method name must start with either findBy or findOneBy!
Thanks in advance for your time and effort.
Check that your MaterialStock have annotation for repository.
<?php
namespace UniflyteBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* MaterialStock
*
* #ORM\Table(name="material_stock")
* #ORM\Entity(repositoryClass="UniflyteBundle\Repository\MaterialStockRepository")
*/
class MaterialStock{
// [...]
}
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();
}
What is the approach to separate the querybuilder if I have some condition that I want to check.
What I want to get is something like this:
public function getProfilePhotoByUserId($userId, $checkApproved = false)
{
$profile = $this->createQueryBuilder('p')
->where('p.user = :userId')
->andWhere('p.profile = 1')
->setParameter('userId', $userId);
if($checkApproved) $profile->andWhere('p.approved = 1');
$profile->getQuery();
return $profile->getOneOrNullResult(Query::HYDRATE_ARRAY);
}
However this shows error on getOneOrNullResult:
"Method not found in querybuilder"
getQuery() return a Doctrine\ORM\Query object.
$query = $profile->getQuery();
return query->getOneOrNullResult(Query::HYDRATE_ARRAY);
or
return $profile->getQuery()->getOneOrNullResult(Query::HYDRATE_ARRAY);
I am not retrieving any values with a simple Doctrine PHPCR query I am executing.
In this piece of code I get all the values from field 'name':
public function getPagesAction()
{
$dm = $this->get('doctrine_phpcr.odm.default_document_manager');
$qb = $dm->createQueryBuilder();
$qb->from()->document('Foo\BarBundle\Document\StandardPage', 'p');
return $this->render(
'FooBarBundle:Toolbar:navigation.html.twig',
array('names' => $qb->getQuery()->execute())
);
}
output: home, mypage, testpage, foo
And with this code I get nothing in return:
public function getPagesAction()
{
$dm = $this->get('doctrine_phpcr.odm.default_document_manager');
$qb = $dm->createQueryBuilder();
$qb->from()->document('Foo\BarBundle\Document\StandardPage', 'p');
$qb->where()->like()->field('p.name')->literal('mypage');
return $this->render(
'FooBarBundle:Toolbar:navigation.html.twig',
array('names' => $qb->getQuery()->execute())
);
}
I am also not receiving any errors. My HTML is plain empty. The query does work when I replace 'p.name' with 'p.title'.
Here is my StandardPage.php on Gist