Symfony2如何实现在doctrine中内置数据

发布时间:2021-08-27 10:28:03 作者:小新
来源:亿速云 阅读:143

这篇文章主要为大家展示了“Symfony2如何实现在doctrine中内置数据”,内容简而易懂,条理清晰,希望能够帮助大家解决疑惑,下面让小编带领大家一起研究并学习一下“Symfony2如何实现在doctrine中内置数据”这篇文章吧。

具体如下:

我们在使用symfony的时候,有时需要在数据库中内置一些数据,那么我们如何在doctrine中设置呢?

所幸,symfony已经为我们封装好了。这里,我们需要用到DoctrineFixturesBundle。

第一步,在composer.json中引入所需的DoctrineFixturesBundle:

{
  "require": {
    "doctrine/doctrine-fixtures-bundle": "2.2.*"
  }
}

第二步,执行composer:

composer update doctrine/doctrine-fixtures-bundle

第三步,在内核(app/AppKernel.php)中注册此bundle:

// ...
public function registerBundles()
{
  $bundles = array(
    // ...
    new Doctrine\Bundle\FixturesBundle\DoctrineFixturesBundle(),
    // ...
  );
  // ...
}

第四步,在需要内置数据的bundle下创建一个PHP类文件,如src/Acme/HelloBundle/DataFixtures/ORM/LoadUserData.php,其代码如下:

// src/Acme/HelloBundle/DataFixtures/ORM/LoadUserData.php
namespace Acme\HelloBundle\DataFixtures\ORM;
use Doctrine\Common\DataFixtures\FixtureInterface;
use Doctrine\Common\Persistence\ObjectManager;
use Acme\HelloBundle\Entity\User;
class LoadUserData implements FixtureInterface
{
  /**
   * {@inheritDoc}
   */
  public function load(ObjectManager $manager)
  {
    $userAdmin = new User();
    $userAdmin->setUsername('admin');
    $userAdmin->setPassword('test');
    $manager->persist($userAdmin);
    $manager->flush();
  }
}

第五步,通过console执行内置数据命令:

php app/console doctrine:fixtures:load #为防止数据库中原先的值被清除,可使用 --append 参数

此命令有以下三个参数:

–fixtures=/path/to/fixture – Use this option to manually specify the directory where the fixtures classes should be loaded;
–append – Use this flag to append data instead of deleting data before loading it (deleting first is the default behavior);
–em=manager_name – Manually specify the entity manager to use for loading the data.

以上是“Symfony2如何实现在doctrine中内置数据”这篇文章的所有内容,感谢各位的阅读!相信大家都有了一定的了解,希望分享的内容对大家有所帮助,如果还想学习更多知识,欢迎关注亿速云行业资讯频道!

推荐阅读:
  1. FOSCommentBundle功能包:设置Doctrine ODM映射(投票)
  2. 怎么使用Joinquant做实盘行情数据

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

symfony2 doctrine

上一篇:shell中如何使用awk实现九九乘法表

下一篇:基于DOM+CSS3如何实现OrgChart组织结构图插件

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》