symfony7通过DBAL查询数据:
通过connection, 其实是实现自: use Doctrine\DBAL\Connection; // 可以在控制器下或service 下手动引入
使用:
use Doctrine\DBAL\Connection;
public function __construct(
private readonly EntityManagerInterface $em,
private readonly Connection $connection,
) {
}
public function test(){
$data = $this->connection->fetchAllAssociative('SELECT * FROM events');
$user = $this->connection->fetchAssociative(
'SELECT * FROM mdpipub.users ORDER BY id ASC LIMIT 1'
);
}
但是在迁移文件下,会自动继承 use Doctrine\Migrations\AbstractMigration; 里面默认有了connection实例
public function up(Schema $schema): void
{
// this up() migration is auto-generated, please modify it to your needs
foreach ($this->connection->fetchAllAssociative('SELECT * FROM events') as $event) {
$this->addSql('INSERT INTO ticket_sections (id, title, `order`, is_special, event_id, created_at, updated_at, created_user_id) VALUES (NULL, "Other tickets", 0, 1, :eventId, :createdAt, :updatedAt, 3555803)', [
'eventId' => $event['id'],
'createdAt' => (new \DateTime())->format('Y-m-d H:i:s'),
'updatedAt' => (new \DateTime())->format('Y-m-d H:i:s'),
]);
}
}
