0
好吧,我有一個數據庫中的幾個表,我不能改變結構。這就是說我正在努力實現的是讓控制器與實體交互,進行自定義連接並返回結果。Symfony2存儲庫和自定義連接
更多細節:
1臺已經ID,用戶名
第二個表已經user_id說明,STAT1,STAT2,STAT3
我想要的是搜索所有用戶在表1中加入表2 。我可以用直接的MySQL做到這一點很容易,但我想知道如何以symfony的方式做到這一點。
好吧,我有一個數據庫中的幾個表,我不能改變結構。這就是說我正在努力實現的是讓控制器與實體交互,進行自定義連接並返回結果。Symfony2存儲庫和自定義連接
更多細節:
1臺已經ID,用戶名
第二個表已經user_id說明,STAT1,STAT2,STAT3
我想要的是搜索所有用戶在表1中加入表2 。我可以用直接的MySQL做到這一點很容易,但我想知道如何以symfony的方式做到這一點。
您需要告訴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
}
不會添加「受保護的$ stats;」給用戶實體嘗試並在該表上添加一列? – chasen 2012-03-11 19:20:15
除非你告訴它。 D2不會自動更改您的數據庫結構。根據你所描述的,$ stats實際上應該是$ stat並且是OneToOne關係。無論如何,您需要閱讀D2手冊以瞭解工作原理。 – Cerad 2012-03-12 14:46:50