gpt4 book ai didi

database - DBAL 从 Symfony2 中的实体连接到数据库

转载 作者:搜寻专家 更新时间:2023-10-30 19:41:34 25 4
gpt4 key购买 nike

我创建了这个实体:

<?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));
}
)

如何从它连接到数据库?

我从这个 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");
}
}

最佳答案

有菜谱文章:http://symfony.com/doc/current/cookbook/doctrine/dbal.html它显示了如何在不通过实体管理器的情况下获取和使用 dbal 连接。

但是和@Rpg600 一样,我有点不明白你为什么要这样做。

您可能应该将此作为一项服务并注入(inject)连接。

也许:

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');

关于database - DBAL 从 Symfony2 中的实体连接到数据库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18030480/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com