Pregunta

I have created this Entity :

<?php
namespace MyProject\MyBundle\Entity;

class User {
    private $id;

    function __construct($id) {
        $this->id = $id;
    }

    public function setName($name) {
        $sql = "UPDATE users SET name=:name WHERE id=:id";
        $stmt = $this->connection->prepare($sql);
        $stmt->execute(array('name' => '$name', 'id' => $this->id));
    }
)

How can I connect to the database from it ?

I call this Entity from this controller :

<?php
namespace MyProject\MyBundle\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use MyProject\MyBundle\Entity;

class MyController extends Controller {
    public function indexAction() {
        $user = new User(1);
        $user->setName("Tom");
    }
}
¿Fue útil?

Solución

There is cookbook article: http://symfony.com/doc/current/cookbook/doctrine/dbal.html which shows how to get and use the dbal connection without going through the entity manager.

But like @Rpg600 I am a bit puzzled at why you are doing such a thing.

You should probably make this a service and inject the connection.

Maybe:

class UserCustomQuery($conn)
{
    public function __construct($conn) { $this->conn = $conn; }

    public function setName($userId,$name)
    {
        ....

Controller:

$userCustomQuery = $this->get('user.custom.query');
$userCustomQuery->setName(1,'Tom');

Otros consejos

You need to use the doctrine Entity Manager http://symfony.com/doc/current/book/doctrine.html#persisting-objects-to-the-database

EDIT: Don't do you query in the model, but inside the entity repository like this:

public function setName(name, id)
{
    $sql = "UPDATE users SET name=:name WHERE id=:id";
    $stmt = $this->getEntityManager()
        ->getConnection()
        ->prepare($sql);

    $stmt->execute(array('name' => $name, 'id' => $id));
}
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top