gpt4 book ai didi

php - 如何使用 Symfony2 创建实体

转载 作者:IT王子 更新时间:2023-10-28 23:53:47 24 4
gpt4 key购买 nike

我的一般问题是如何使用 symfony2 创建实体和存储库?

  • 如何使用带有 doctrine orm 的 schema.yml 创建实体/存储库?我必须在哪里保存 schema.yml 文件?在控制台中输入哪些命令?
  • 我创建了一个没有 schema.yml 的类实体之后要做什么?命令!?
  • 当实体对所有项目通用或特定于包时,我必须在哪里保存我的实体/存储库文件?

最佳答案

我的解决方案(我不知道这是否是好的,最佳实践!?)

YML

使用此代码(通过示例)在 HelloBundle/Resources/config/doctrine/metadata/orm 中创建“Entities.User.dcm.yml”文件:

Entities\User:
type: entity
table: users
id:
id:
type: integer
generator:
strategy: AUTO
fields:
name:
type: string
length: 50

然后

php app/console doctrine:mapping:import "HelloBundle" yml

php app/console doctrine:generate:entities "HelloBundle"

然后,您可以在您的 Controller 中测试它:

$user = new \Sensio\HelloBundle\Entity\User;
$user->setName('Acubens');
$em = $this->get('doctrine.orm.entity_manager');
$em->persist($user);
$em->flush();

或使用 PHP

使用此代码在 HelloBundle\Entity 中创建“User.php”文件

// Sensio/HelloBundle/Entity/User.php
namespace Sensio\HelloBundle\Entity;

/**
* @orm:Entity
*/
class User
{
/**
* @orm:Id
* @orm:Column(type="integer")
* @orm:GeneratedValue(strategy="IDENTITY")
*/
protected $id;

/**
* @orm:Column(type="string", length="255")
*/
protected $name;
}

然后

php app/console doctrine:mapping:import "HelloBundle"

这将在“HelloBundle/Resources/config/doctrine/metadata/orm”中生成

<?xml version="1.0" encoding="utf-8"?>
<doctrine-mapping xmlns="http://doctrine-project.org/schemas/orm/doctrine-mapping" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://doctrine-project.org/schemas/orm/doctrine-mapping http://doctrine-project.org/schemas/orm/doctrine-mapping.xsd">
<entity name="Sensio\HelloBundle\Entity\User" table="user">
<change-tracking-policy>DEFERRED_IMPLICIT</change-tracking-policy>
<id name="id" type="integer" column="id">
<generator strategy="IDENTITY"/>
</id>
<field name="name" type="string" column="name" length="255"/>
<lifecycle-callbacks/>
</entity>
</doctrine-mapping>

然后删除User.php

php app/console doctrine:generate:entities "HelloBundle"

在你有一个新的漂亮文件 User.php 之后

<?php

namespace Sensio\HelloBundle\Entity;

/**
* Sensio\HelloBundle\Entity\User
*/
class User
{
/**
* @var string $name
*/
private $name;

/**
* @var integer $id
*/
private $id;


/**
* Set name
*
* @param string $name
*/
public function setName($name)
{
$this->name = $name;
}

/**
* Get name
*
* @return string $name
*/
public function getName()
{
return $this->name;
}

/**
* Get id
*
* @return integer $id
*/
public function getId()
{
return $this->id;
}
}

你好吗?为什么我必须在命令中指定 HelloBundle?

ps:我的config.yml

doctrine.dbal:
driver: pdo_mysql
dbname: sf2
user: root
password:
logging: %kernel.debug%
doctrine.orm:
auto_generate_proxy_classes: %kernel.debug%
mappings:
HelloBundle: ~

关于php - 如何使用 Symfony2 创建实体,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4983998/

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