Doctrine ORM zend framework entitymanager findby multiple conditions - zend-framework

I'm querying the database with 2 findby's, is there a way to do it in one findby with 2 conditions?
$this->entityManager->getRepository(User::class)->findOneByConfirmtoken($token)
&& $this->entityManager->getRepository(User::class)->findOneById($id)

->findBy([
'property1' => 'value1',
'property2' => 'value2',
])
See the docs about using conditions

You can pass the array of values to findBy method. I also recommend you write your own repositories in specific cases. It is useful for more complex queries. In this case it would be looks like:
public function findOneByIdAndConfirmationToken(int $userId, string $confirmationToken): ?User
{
return $this->getEntityManager()
->createQueryBuilder()
->select('u')
->from(User::class, 'u')
->where('u.id = :userId')
->andWhere('u.confirmationToken = :confirmationToken')
->setParameter('userId', $userId, PDO::PARAM_INT)
->setParameter('confirmationToken', $confirmationToken, PDO::PARAM_STR)
->getQuery()
->getOneOrNullResult();
}

Related

Laravel 8 withSum relation default value 0

Will laravel 8's withSum function supports default value?
use App\Models\Post;
$posts = Post::withSum('comments', 'votes')->get();
In this relation laravel returns 'comments_sum_votes' as null if a 'post' has no 'comments'.Can we set it to return 0?
I just bumped into this.
While an eloquent accessor may work in certain situations, doing ORDER BY or GROUP BY on this column still wouldn't return correct results (because the database query would still return null when no records are found).
Alternatively, you could do COALESCE yourself like so, which is more efficient:
$post = Post::query()
->withSum([
'comments' => fn ($query) => $query->select(DB::raw('COALESCE(SUM(votes), 0)')),
], 'votes')
->get();
Ref

Doctrine MongoDB where two fields are equal

How do you create a where condition in Doctrine ODM to find only documents where two fields are equal?
A document exists with two int fields alpha and beta, I want to select all documents where these two fields are equal.
I've tried the following but it returns no results:
$qb = $this->createQueryBuilder();
$qb
->field('alpha')->in($alphaIds)
->where('this.alpha === this.beta')
->sort('id', 'DESC');
return $qb->getQuery()->execute();
This questions shows how to do it outside of Doctrine where alpha and beta are not equal https://stackoverflow.com/a/8433182/1283381
Use the Query Expressions in Doctrine\MongoDB\Query\Expr class to create the where() expression via the expr() method as follows:
$qb = $this->createQueryBuilder();
$qb->addAnd(
$qb->expr()
->field('alpha')->in($alphaIds)
->where('this.alpha === this.beta')
)
->sort('id', 'DESC');
return $qb->getQuery()->execute();

How to use zend_db_select to update when there is two clause

I want to update an entry in the table when 2 conditions are met.
I have this statement, but it is only for one where condition
$this->dbo->update('mytable', $data, $this->dbo->quoteInto('id= ?', $id));
Instead of just checking where for just "id", i want to check for userid also..
Appreciate any help.
Something similar to this should work as the $where argument will accept and parse an array, reference the _whereExpr() method in Zend_Db_Adapter_Abstract for the code on how the $where arg is processed:
$this->dbo->update('mytable', $data, array('id= ?'=> $id, 'user_id=?'=>$userId));
I'm going to suggest that you may wish to alter you approach and use the save() method of Zend_Db_Table_Row instead of update. Here's an example.
public function saveUser($id, array $userData, $userId = null)
{
//$this->getDbAdapter is a placeholder for your choice of db adapters, I suggest a DbTable model that extends Zend_Db_Table_Abstract
$select = $this->getDbAdapter()->select();
//if userId is not null build a where clause
if (!is_null($userId)) {
$select->where('user_id = ?', $userId);
}
//build where clause for primary key, two where() in select() will be 'AND' use orWhere() for 'OR'
$select->where('id = ?', $id);
//fetch the row you wish to alter
$row = $this->getDbAdapter()->fetchRow($select);
//assign the data to the row, you can update any or all columns
$row->username = $userData[username];
$row->user_id = $userData[user_id];
//ect...
//save the new data to the row, will only update changed coluns
$row->save();
//return the whole for use in other ways, save() typically only returnbs the primary key.
return $row;
}
Yes this method is a little more verbose and maybe a touch more complicated. However as you start bumping up against the limits of 'INSERT' and 'UPDATE', save() can provide some useful functionality.

How to update embedded document in MongoDB with Doctrine ODM

I'm unable to find how to update embedded documents with Doctrine Mongo ODM in Symfony2. I have a class called Page with many embedded documents "Comments" and I want to use createQueryBuilder to update specific comment. Here is a simple class that I have:
class Page
{
protected $id;
/** #MongoDB\EmbedMany */
private $pageComment = array();
}
I searched the whole internet, but I don't see to find any info on how to update subdocuments of a document with Doctrine ODM query builder. I will be thankful for any information as I'm new to both Doctrine and Mongo. In simple words I want to update specific comment in a page after searching for it by id.
Thanks in advance for your help!
You can update only one field at time (instead of pageComment.$):
$this->createQueryBuilder('page')
->update()
->field('id')->equals($pageId)
->field('pageComment.id')->equals($pageCommentId)
->field("pageComment.$.field1")->set($field1)
->getQuery()
->execute();
If you wan to use queryBuilder use this
$dm->createQueryBuilder('Page')
->update()
->field('page.pageComment')->set( <$newupdatePageCommentObj> )
->field('id')->equals('<matchedId>')
->getQuery()
->execute();
Or When you generate setters and getters for a EmbedMany member variable it will generate add and remove member functions inside your class. so in your case these will be member functions:
public function addPageComment(type_hint_with_your_pageComment_document $pageComment )
{
$this->pageComment[] = $pageComment;
}
public function removePageComment( type_hint_with_your_pageComment_document $pageComment )
{
$this->items->removeElement( $pageComment );
}
So you can use addPageComment() function which will add it if does not exists and will update it will its already there.
$yourArrayPageComment = array(
"id" => new \MongoId($pageCommentId),
"field1" => $field1,
...
)
$this->createQueryBuilder('page')
->update()
->field('id')->equals($pageId)
->field('pageComment.id')->equals($pageCommentId)
->field("pageComment.$")->set($yourArrayPageComment)
->getQuery()
->execute();

Is it possible to use sort() on multiple fields in Doctrine 2 ODM?

I am doing a query on a result document in my doctrine mongodb *odm*. There are two indexed fields in the document which I would like to use in sort. I have written something like:
$results = $this->createQueryBuilder('Document\Score')
->sort('finalScore', 'desc')
->sort('date', 'desc')
->getQuery()
->execute();
Here the second sort() function overrides the first one and the designated result is never found.
Thanks in advance for the nice help.
Try this
$qb = $this->createQueryBuilder('Document\Score');
$qb->sort(array(
'finalScore' => 'desc',
'date' => 'desc',
));
$results = $qb->getQuery()->execute();