2012-03-11 105 views
0

好吧,我有一个数据库中的几个表,我不能改变结构。这就是说我正在努力实现的是让控制器与实体交互,进行自定义连接并返回结果。Symfony2存储库和自定义连接

更多细节:

1台已经ID,用户名

第二个表已经user_id说明,STAT1,STAT2,STAT3

我想要的是搜索所有用户在表1中加入表2 。我可以用直接的MySQL做到这一点很容易,但我想知道如何以symfony的方式做到这一点。

回答

1

您需要告诉Doctrine在哪里找到每条信息,以便每次实例化新的User对象时都可以加载所有属性。换句话说,你需要添加自定义的Doctrine映射信息。假设您将映射信息作为内嵌注释添加到用户模型类中,代码如下所示:

//in User.php 

use Doctrine\ORM\Mapping as ORM; 

/** 
* @ORM\Entity 
* @ORM\Table(name="first_table_name") 
*/ 
class User 
{ 
    /** 
    * @ORM\Id 
    * @ORM\Column(type="integer") 
    * @ORM\GeneratedValue(strategy="AUTO") 
    */ 
    protected $id; 

    /** 
    * @ORM\Column(type="string") 
    */ 
    protected $username; 

    /** 
    * @ORM\OneToMany(targetEntity="UserStats") 
    */ 
    protected $stats; 

    //also define getters and setters for the above, of course 
} 



//in UserStats.php 

use Doctrine\ORM\Mapping as ORM; 

/** 
* @ORM\Entity 
* @ORM\Table(name="table_two_name") 
*/ 
class UserStats 
{ 
    /** 
     * I'm pretty sure doctrine will require that you add an Id column to table_two, 
     * which is what this is. If you can't add an Id, I'm not sure it'll work... 
     * @ORM\Id 
     * @ORM\Column(type="integer") 
     * @ORM\GeneratedValue 
     */ 
    protected $id; 

    /** 
     * @ORM\ManyToOne(targetEntity="User") 
     * @ORM\JoinColumn(name="user_id", referencedColumnName="id") 
     */ 
    protected $user; 

    /** 
     * The below assumes your stats are strings. If not, change the type attribute. 
     * @ORM\Column(type="string") 
     */ 
    protected $stat1; 

    /** 
     * @ORM\Column(type="string") 
     */ 
    protected $stat2; 

    /** 
     * @ORM\Column(type="string") 
     */ 
    protected $stat3; 

    //include appropriate getters/setters here too 
} 
+0

不会添加“受保护的$ stats;”给用户实体尝试并在该表上添加一列? – chasen 2012-03-11 19:20:15

+1

除非你告诉它。 D2不会自动更改您的数据库结构。根据你所描述的,$ stats实际上应该是$ stat并且是OneToOne关系。无论如何,您需要阅读D2手册以了解工作原理。 – Cerad 2012-03-12 14:46:50