I have some table store_section(id,parent_id,label), I want to change some row, set parent_id=null.
I trying to:
$record = $table->getTable()->find( $id );
$record->parent_id = null;
$record->save();
But this isn't work. How can I do set NULL into the table in Doctrine, in example above, parent_id becomes =0 (not =NULL)?
Thnx for the responses!
I would try one of the following:
1:
$record = $table->getTable()->find( $id );
$record->parent_id = new Doctrine_Null();
$record->save();
2:
$record = $table->getTable()->find( $id );
$record->parent_id = "NULL";
$record->save();
I have not tested these, but I do recall having a similar issue prior, just cannot recall how I solved it. Hope this helps!
You can use method set('u.name', 'NULL')
For example:
Doctrine_Query::create()->update('User u')->set('u.name', 'NULL')->where('u.id = ?',$id);
Doctrine_Null only has two methods, and the one that seems to relate is the __toString method. So in order to activate the magic method you need to cast as a string:
$record = $table->getTable()->find( $id );
$record->parent_id = (string) new Doctrine_Null;
$record->save();
But honestly there is no reason, as Doctrine_Null just abstracts an empty string ''. I can only assume that it only works in this scenario because parent_id is not enforcing a NULL attribute.
Setting a value of 'NULL' appears to work but is actually a string and not NULL.
'NULL' !== null
Give it a shot, if you insert 'NULL' into one row, and another row is a "natural NULL", and you pull both rows out of the table and do a var_dump(serialize()) on each, you will see one is a natural null and other is actually a string.
If you want to maintain consistency and enforce natural nulls, use this instead:
$record = $table->getTable()->find( $id );
$record->parent_id = new Doctrine_Expression('NULL');
$record->save();
in this case, when the field is a relation. I have complished this task with:
$record->Parent = null;
$record->save();
Above Parent is the relation name.
In Doctrine2 Using the query builder, you can also directly update the value in the db.
$qb = // $this->connection->createQueryBuilder(); or $this->em->createQueryBuilder();
$qb->update('store_section', 's')
->set('s.parent_id', ':parent_id')
->andWhere('s.id', ':id'));
$qb->setParameter('parent_id', null);
$qb->setParameter('id', $id);
$qb->execute();
$record->setParentId(null);
$record->save();
Related
I have a need to update a table like this :
UPDATE table SET column = value WHERE first_id = 1 AND second_id = 2
Is it possible to do this in Laravel using eloquent model? If it is how can i do this?
I was trying with :
$object = Model::where('first_id' , 1)->where('second_id' , 2)->get();
$object->column = $value
$object->save();
Yes you can do it. Here is how you can do it.
Model::where('first_id', 1)
->where('second_id', 2)
->update(['column' => 'yourValue']);
You are getting a collection. You can update the column of each of those collection. You can only get the first one collection using first.
foreach($object as $obj){
$obj->column = $value;
$obj->save();
}
Or
$object = Model::where('first_id' , 1)->where('second_id' , 2)->first();
$obect->column =$value;
$object->save();
I have a table, myTable, with a single column, myColumn, with a single row.
I want to change the value of myColumn in that first (and only) row.
I tried this, but nothing happens:
$myNewValue = 'foo';
$this->db->update('myColumn', $myNewValue);
What am I doing wrong?
Obviously it must have something to do with not specifying which table, but I don't know how to do that.
Codeigniter's update() needs to follow this syntax:
update([$table = ''[, $set = NULL[, $where = NULL[, $limit = NULL]]]])
Parameters:
$table (string) – Table name
$set (array) – An associative array of field/value pairs
$where (string) – The WHERE clause
$limit (int) – The LIMIT clause
so besides of adding the correct table name, you'd need to send update data as an array, using this approach:
$myNewValue = array('myColumn'=>'foo');
$this->db->update('myTable', $myNewValue);
Figured out how to do it:
$this->db->update('myTable', [
'myColumn' => $myNewValue,
]);
Try this method, it is my favorite format.
$where = array(
'column_id'=$id
);
$data = array(
'column_name'=$data
);
$this->db->update('table_name', $data,$where);
I have in my table "Artiste" one column "valideAdmin" who takes value 1 or 0.
I try to make a simple count to return the number of entries in my table where "valideAdmin" is to 1:
$repo = $this ->getDoctrine()
->getManager()
->getRepository('ProjectMainBundle:Artiste');
$qb = $repo->createQueryBuilder('valideAdmin');
$qb->select('COUNT(valideAdmin)');
$qb->where('valideAdmin=1');
$count = $qb->getQuery()->getSingleScalarResult();
return array(
'count' => $count
);
But it always "1" who's return...
Without where clause, I have the total count of the entries of the table, but valideAdmin can be 0 or 1. I only want the count number where valideAdmin=1
Thanks for help
createQueryBuilder()'s first parameter is the alias that you want your entity to take (ie.: a short name to be used to refer to your entity in the query).
What you need to do is set a proper alias for your entity (for example a for Artiste) and then COUNT() the instances of your entity where the property (not the column) valideAdmin is set to one:
$repo = $this ->getDoctrine()
->getManager()
->getRepository('ProjectMainBundle:Artiste');
$qb = $repo->createQueryBuilder('a');
$qb->select('COUNT(a)');
$qb->where('a.valideAdmin = :valideAdmin');
$qb->setParameter('valideAdmin', 1);
$count = $qb->getQuery()->getSingleScalarResult();
Remember that DQL runs queries on entities. The DQL your write is then translated into SQL to query the underlying data source after.
Also you can fetch all date then use of COUNT function in PHP
This method has an advantage.You do not have to use a complex query.
You have all the information with count columns
$repositoryArtiste = $this->getDoctrine()
->getRepository('ProjectMainBundle:Artiste');
$queryArtiste= $repositoryArtiste->createQueryBuilder('a')
->Where('a.valideAdmin = :valideAdmin')
->setParameter('valideAdmin',1)
->getQuery();
$Artiste = $queryArtiste->getResult();
var_dump(count($Artiste));
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)
I am finding that I often need to select a field, based on a condition other than the id.
So, $user = User::where('last_login', $lastLogin)->where('last_warning', $lastWarning)->get(); works perfectly.
That is until you set one of the where's to allow nulls (let's do last_login).
That is, it can either have a value or be null.
That means you need to use one of two function where() or whereNull() and to do that you need to break the chain, so it becomes
$user = User::where('last_warning', $lastWarning);
is_null($lastLogin) ? $user->whereNull('last_login') : $user->where('last_login', $lastLogin);
$user = $user->get();
I am wondering if where has a way to deal with this? as currently if you pass null through to where you get where column = null which doesn't work!
Two options:
Option 1:
if (is_null($lastLogin))
{
$user = User::whereNull('last_login')->where('last_warning', $lastWarning)->get();
}
else
{
$user = User::where('last_login', $lastLogin)->where('last_warning', $lastWarning)->get();
}
Option 2:
$user = User::where('last_login', (is_null($lastLogin) ? 'IS' : '=') ,$lastLogin)->where('last_warning', $lastWarning)->get();
Option two makes the query 'where last_login = x' or 'where last_login IS null'
You can try this:
User::where(function($query) use ($lastlogin)
{
if(is_null($lastLogin))
{
$query->whereNull('last_login');
}
else
{
$query->where('last_login', '=', $lastLogin);
}
})->get();
It is a good solution when dealing with long queries with more than one parameter.
You can use DB::raw() as well:
User::where('last_login', 'IS', DB::raw('null'))->where_last_warning($lastWarning)->get();
As of Laravel 5.3 you are now able to ->where('column', null) to automatically produce WHERE column IS NULL.
If using variable, make sure that they have PHP null strict value.