From TYPO3 DB wrapper to doctrine. Select Statement - php

I have to migrate some code from the TYPO3 DB wrapper to Doctrine with the QueryBuilder. In my database are four entries.
The original statement:
$statementToMigrate = $GLOBALS['TYPO3_DB']->exec_SELECTgetRows(
'job_id,uid,pid,hash',
'tx_test',
'deleted = 0',
null,
null,
null,
'job_id'
);
And my QueryBuilder version:
$table = 'tx_test';
$queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)
->getQueryBuilderForTable($table);
$sql = $queryBuilder
->select(
"job_id,uid,pid,hash"
)
->from($table)
->where(
$queryBuilder->expr()->eq('deleted', 0)
)
->execute()
->fetchAll();
The original statement provides me all four entries.
The new version only two. Where are the differences?
And how can I set " $uidIndexField= ''" in doctrine?
Solution:
I added
$queryBuilder
->getRestrictions()
->removeByType(StartTimeRestriction::class)
->removeByType(EndTimeRestriction::class);
and now it works

hi the Querybuilder takes into account the common "restrictions" like start/end date, language, hidden/ deleted. i guess you records are filtered out by some other restrictions.
see here for more about restrictions: https://docs.typo3.org/m/typo3/reference-coreapi/master/en-us/ApiOverview/Database/RestrictionBuilder/Index.html#database-restriction-builder

And how can I set " $uidIndexField= ''" in doctrine?
Doctrine doesn't have such functionality by itself, afaik. Earlier in old Typo3 in the exec_SELECTgetRows method the array was simply traversed to set that index before return. Now it seems you have to do the same on your own. I searched for quite a long time to find good, fast and hopefully native way to achieve that effect with no luck, but finally I stumbled upon that snip:
...
// return $preparedStatement->fetchAll(\PDO::FETCH_ASSOC);
$result = $preparedStatement->fetchAll(\PDO::FETCH_ASSOC);
return array_column($result, null, $uidIndexField);
and finally it looks like that does the trick.

Related

PHP Laravel Query Cloning Not Working as Expected

So I'm coming across an issue with QueryBuilder cloning. He's my situation, I need to run 3 separate queries, all based off a single "BaseQuery":
$baseQuery = $model->selectRaw("column")->whereNull("deleted_at");
$query1 = clone($baseQuery);
$query1Results = $query1->where("condition", "=", 0)->get();
$query2 = clone($baseQuery);
$query2Results = $query2->where("condition2", "=", 1)->get();
$query3 = clone($baseQuery);
$query3Results = $query3->where("condition3", "=", 0)->get();
By the time I get to $query3, it has 3 where statements. Substituting $query3 ... get() with $query3 ... ->toSql(); shows these results:
SELECT `column` FROM `models` WHERE `deleted_at` IS NULL AND `condition` = ? AND `condition2` = ? AND `condition3` = ?;
It seems that even though I am defining each $queryX as a clone of $baseQuery, the additional ->where() clause is being applied to each of the queries. I've tried doing the clone() before appending any of the ->where() clauses, but that doesn't have any affect.
Is there a way to clone() something and ensure that it creates a new instance? It looks like clone() isn't separating $baseQuery from $queryX, so the ->where()s are being applied to every subsequent copy, even though each should be a new query with only the ->whereNull() clause.
Another interesting point is that running
\Log::info($baseQuery == $queryX);
After each modification returns true (=== is false though)
You should use scopes here.
Local scopes allow you to define common sets of constraints that you may easily re-use throughout your application. For example, you may need to frequently retrieve all users that are considered "popular". To define a scope, simply prefix an Eloquent model method with scope
public function scopeBase($q)
{
return $q->selectRaw('column')->whereNull('deleted_at');
}
Then just do something like this:
$query1Results = $model->where('condition', 0)->base()->get();
$query2Results = $model->where('condition2', 1)->base()->get();
$query3Results = $model->where('condition3', 0)->base()->get();

Laravel 4 - How to turn timestamps off to update an entire collection

I'm trying to do a mass update on an eloquent collection.
So I have my query, which looks a bit like this:
\Responder::with('details')
->where('job_number', $project->job_number)
->where('batch_id', ((int) $batch_id) - 1)
->where('updated_at', '<=', $target_time)
->whereHas('transactions', function($q) {
$q->where('status', 'success');
}, '<', 1)
->whereHas('details', function($q) {
$q->where('email', '<>', '');
});
This query object is stored as $query (because I'm re-using it - the same reason I dont want to switch how I'm doing the query), I am then performing an update on the collection, e.g.
$query->update(array('batch_id' => $batch_id));
This works great except it updates all the 'updated_at' timestamps. Now i like the timestamps, they are used extensively elsewhere, so i cant turn them off all together but I thought I could disable them temporarily but I've tried the following:
$query->timestamps = false;
$query->update(array('email_drop_off_index' => $batch_id));
and I can confirm that doesn't work, is there a way to do this?
Any help much appreciated
timestamps = false should be made on your model, but what you are doing is setting the value on the query builder. That's why it is not being picked up.
timestamps is an instance variable so you can't set it statically, and I don't think there is a built-in way to do it from the query builder. So I suggest try instantiating the model first, then create a new query from it, like this:
$responder = new \Responder;
$responder->timestamps = false;
$query = $responder->newQuery()
->with('details')
->where('job_number', $project->job_number)
...; // the rest of your wheres
$query->update(array('email_drop_off_index' => $batch_id));
Here's a possible solution: subclass your Responder model and turn off timestamps in the subclass.
class MassUpdateResponder extends Responder
{
public $timestamps = false;
}
Then use your new class to do the updates. This seems like a bit of a hack, but it should work.
BTW, doing an update like the following worked for me:
$query->timestamps = false;
$query->value = "new value";
$query->save();
The update() method may be doing something different that's causing it to ignore the value of $timestamps.

How to update a field in doctrine to set it null

I want to set null to a field in doctrine and here is the sentence
$em = $this->getDoctrine()->getManager();
$qb = $em->createQueryBuilder();
$query = $qb->update('Model\Example', 'u')->set('u.deletedAt', ':deletedAt')
->where("u.id IN (:ids)")->setParameter('deletedAt', null)
->setParameter('ids', $ids)
->getQuery();
$query->execute();
i think that this code should do the job, but im getting this exception
An exception occurred while executing 'UPDATE example SET deleted_at = ?
WHERE (id IN (?)) AND (example.deleted_at IS NULL)' with params
[null, "5,6"]: SQLSTATE[22P02]: Invalid text representation: 7 ERROR:
la sintaxis de entrada no es válida para integer: «5,6»
first of all why doctrine is adding that AND (example.deleted_at IS NULL) am i doing something wrong ?
Your original query looks like it should work. I duplicated and tested with:
$em = $this->getService('doctrine.orm.entity_manager');
$qb = $em->createQueryBuilder();
$qb->update('Cerad\Bundle\PersonBundle\Entity\Person','person');
$qb->set('person.verified',':verified');
$qb->setParameter('verified',null);
$qb->where('person.id IN (:ids)');
$qb->setParameter('ids',array(1,2,3));
echo $qb->getQuery()->getSql(); // UPDATE persons SET verified = ? WHERE id IN (?)
$qb->getQuery()->execute();
Works as expected.
Are you sure you copy/pasted your exact code? No editing after the fact? Verify your ids array really is an array of integers. That is the only spot I could see where there might be an issue. And do make sure your error is coming from the code you posted. Maybe something else is going on? Try isolating your code in a command object. And of course deletedAt has it's is nullable set to true?
There is no real need to use the expr object for this case. Doctrine 2 correctly handles arrays for IN statements.
====================================
I suspect you have $ids = '5,6'? Try setting it to: $ids = array(5,6); Though even with a string I don't see how it's messing up the query.
When you set the value with PHP null script , it's not understood for doctrine because when transforming to the native sql ,he will not replace null with null value as string , so to resolve , pass the null value as string like
$qb->set('q.deletedAt','NULL');
thanks #Cerad the problem was that i was using the soft-delete extension from StofDoctrineExtensionsBundle and the bundle was adding the soft delete filter, so i just disabled the soft delete filter and now it works as expected,posting the solution many thanks.
$em = $this->getDoctrine()->getManager();
$em->getFilters()->disable('softdeleteable'); // this was the problem when you use the soft delete extension you need to disable the filter if you want to reactivate deleted records
$qb = $em->createQueryBuilder();
$qb->update('Model\Example', 'q');
$qb->set('q.deletedAt',':deletedAt');
$qb->setParameter('deletedAt',null);
$qb->where("q.id IN (:ids)");
$qb->setParameter('ids', $ids);
the problem is that you $ids is a string. you can make:
$arrayOfIds = explode(",", $ids);
and after in you update query:
->setParameter('ids', $arrayOfIds)

Codeigniter - Active record - sql - complex join

I have a function that retrieves all tags from a table:
function global_popular_tags() {
$this->db->select('tags.*, COUNT(tags.id) AS count');
$this->db->from('tags');
$this->db->join('tags_to_work', 'tags.id = tags_to_work.tag_id');
$this->db->group_by('tags.id');
$this->db->order_by('count', 'desc');
$query = $this->db->get()->result_array();
return $query;
}
I have another table called 'work'. The 'work' table has a 'draft' column with values of either 1 or 0. I want the COUNT(tags.id) to take into account whether the work with the specific tag is in draft mode (1) or not.
Say there are 10 pieces of work tagged with, for example, 'design'. The COUNT will be 10. But 2 of these pieces of work are in draft mode, so the COUNT should really be 8. How do I manage this?
Try changing:
$this->db->from('tags');
$this->db->join('tags_to_work', 'tags.id = tags_to_work.tag_id');
To:
$this->db->from('tags, work');
$this->db->join('tags_to_work', 'tags.id=tags_to_work.tag_id AND work.id=tags_to_work.work_id');
And Adding:
$this->db->where('work.drafts', 0);
You can use pure sql instead of using the active record class, I myself are working with CI for over 2 years and most of the time I am avoiding the active record class, cause straight sql is much easier to debug and write complex queries.
This is how i would use it.
$sql = "SELECT...your sql here";
$q = $this->db->query($sql);
...
//Do something with your query here

Doctrine ORM, two different querys produce the same result set

I'm using Doctrine 1.2 and Symfony 1.4.
In my action, I have two different query that return different result set. Somehow the second query seem to change the result (or the reference?) of the first one and I don't have any clue why..
Here is an example:
$this->categories = Doctrine_Query::create()
->from('Categorie AS c')
->innerJoin('c.Activite AS a')
->where('a.archive = ?', false)
->execute();
print_r($this->categories->toArray()); // Return $this->categories results, normal behavior.
$this->evil_query = Doctrine_Query::create()
->from('Categorie AS c')
->innerJoin('c.Activite AS a')
->where('a.archive = ?', true)
->execute();
print_r($this->categories->toArray()); // Should be the same as before, but it return $this->evil_query results instead!
Why Doctrine behave this way ? It's totally driving me crazy. Thanks!
To make it simple it seem like the Query 2 are hijacking the Query 1 result.
Use something like this between queries ($em - entity manager):
$em->clear(); // Detaches all objects from Doctrine!
http://docs.doctrine-project.org/en/2.0.x/reference/batch-processing.html
In the API docs for the toArray() method in Doctrine_Collection it says:
Mimics the result of a $query->execute(array(), Doctrine_Core::HYDRATE_ARRAY);
I suspect to answer this question to your satisfaction you're going to have to go through the source code.
This seems like it has to be an issue of $this->categories and $this->evil_query pointing to the same place. What are the results of $this->evil_query === $this->categories and $this->evil_query == $this->categories?
Hubert, have you tried storing the query into a separate variable and then calling the execute() method on it?
I mean something like:
$good_query = Doctrine_Query::create()
->from('...')
->innerJoin('...')
->where('...', false)
;
$evil_query = Doctrine_Query::create()
->from('...')
->innerJoin('...')
->where('...', true)
;
$this->categories = $good_query->execute();
$this->evil_query = $evil_query->execute();
It seems like both attributes (categories and evil_query) are pointing at the same object.
Erm, after both queries you print_r the result of the first query - change the last line to print_r($this->evil_query->toArray()); to see the difference :)

Categories