Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

$em->remove() symfony2 erasing all rows

I have an issue when erasing something from a BD.

The problem is that it not only erase the object i looked for (using findOneBy), but all the objects related to the principal id.

//---Controller

$new = $this->getDoctrine()->getManager();
$OBJcar = $new->getRepository('SomeOtherBundle:CarEntityClass')
    ->findOneBy(array('idOwner' => $idowner, 'idCar' => $idcar));
if($OBJcar){
  $new->remove($OBJcar);
  $new->flush();
  $msj="The car for an specific owner has been erased.";
}

//---Profiler (Query)

"START TRANSACTION"
  Parameters: { }
  Time: 0.22 ms
DELETE FROM schema.CarTable WHERE id_owner = ?
  Parameters: ['123456']
  Time: 0.63 ms
"COMMIT"
  Parameters: { }
  Time: 0.63 ms

How to erase the one row i am getting from the db?

like image 394
ib.programmer Avatar asked Jul 16 '13 19:07

ib.programmer


2 Answers

I voted down the answer above, because I'm tired of people using string DQLs. It's not standartized, non-object oriented(even though in background dql operates with objects), it doesn't use caching mechanisms query builder provides, it's non-flexible and simply looks unclean.

Here is the "right way"(IMHO):

  1. You add the repository class for entity
  2. You add the method you need with a query builder in it
  3. You call the method while passing parameters needed for specific REPOSITORY OBJECT ORIENTED ACTION
  4. You get an easy-to-handle result

Here's the code:

namespace ProjectName\BundleName\Repository;
use Doctrine\ORM\EntityRepository;

class CarRepository extends EntityRepository
{
    public function deleteCarWithOwner($ownerId,$carId)
    {
        $isDeleted = $this->createQueryBuilder("car")
            ->delete()
            ->where('car.id  = :carId')->setParameter("carId", $carId)
            ->andWhere('car.idOwner = :ownerId')->setParameter("ownerId", $ownerId)
            ->getQuery()->execute();

        return $isDeleted;
    }
}

Also, refer to http://doctrine-orm.readthedocs.org/en/latest/reference/query-builder.html for query builder details. There are a lot of "pros" and I see no "cons" for using builder.

LATE UPDATE

Also, a lot of Doctrine's entity events are not dispatched when using DQL.

like image 187
drakonli Avatar answered Nov 08 '22 19:11

drakonli


Use DQL

$query = $em->createQuery('DELETE SomeOtherBundle:CarEntityClass c WHERE c.idOwner = 4 AND c.id = 10');
$query->execute(); 

This will remove only single car with ID 10 and owner with ID 4.

like image 2
Norbert Orzechowicz Avatar answered Nov 08 '22 18:11

Norbert Orzechowicz