我是Symfony2的新手,但我使用Rails。我想在Symfony2中做这样的事情:
class Manager < ActiveRecord::Base
has_many :employees
end
然后像这样问对象:
m = Manager.find(1)
# Sends SQL query SELECT COUNT * FROM EMPLOYEES WHERE MANAGER_ID = 1
count = m.employees.count
# Sends SQL query SELECT * FROM EMPLOYEES WHERE MANAGER_ID = 1
m.employees.each do |e|
puts e.name
end
我在Symfony2中有这段代码...
/**
* @Entity @Table(name="Manager")
*/
class Manager
{
/**
* @Id @Column(type="integer") @GeneratedValue
*/
public $id;
/**
* @Column(type="string")
*/
public $description;
/**
* @OneToMany(targetEntity="User", mappedBy="manager")
* @var User[]
*/
private $employees;
}
我怎样才能在Symfony2中实现这些(上述)功能(在RoR中很容易由其ORM制作)?
感谢您的帮助...
神话冲刺
m = Manager.find(1)
# Sends SQL query SELECT * FROM EMPLOYEES WHERE MANAGER_ID = 1
m.employees.each do |e|
puts e.name
end
似乎我们正在寻找取决于经理 ID 的员工。
让我们从一对多的双向关系开始(教义文档)
<?php
/** @Entity **/
class Manager
{
// ...
/**
* @OneToMany(targetEntity="Employee", mappedBy="manager")
**/
private $employees;
// ...
public function __construct() {
$this->employees = new DoctrineCommonCollectionsArrayCollection();
}
}
/** @Entity **/
class Employee
{
// ...
/**
* @ManyToOne(targetEntity="Manager", inversedBy="employees")
* @JoinColumn(name="manager_id", referencedColumnName="id")
**/
private $manager;
// ...
}
控制器
<?php
// src/Acme/DemoBundle/Controller/ManagerController.php
// ...
public function showAllEmployeesForManagerAction($managerId)
{
$repo = $this->getDoctrine()->getRepository('AcmeDemoBundle:Manager');
$manager = $repo->find(managerId);
$employees = $manager->getEmployees();
// counting employees
$employeesNumber = count($employees); // not passed to template
return $this->render('AcmeDemoBundle:Employees:list.html.twig', array(
'manager' => $manager,
'employees' => $employees,
));
}
模板
{# src/Acme/DemoBundle/Resources/views/Employees/list.html.twig #}
{% extend '::base.html.twig' %}
{% block body -%}
<h2>Employees depending on Manager {{manager.name}}</h2>
<p>Number of employees : {{employees|length}}</p>
<ul>
{% for employee in employees %}
<li>{{ employee.name }}</li>
{% endfor %}
</ul>
{% endblock %}
希望这对你有用。
大卫
如果你使用 Dcotrine2 orm,它看起来像这样:
<?php
// src/Acme/DemoBundle/Controller/ManagerController.php
// ...
public function showAllAction()
{
$repo = $this->getDoctrine()->getRepository('AcmeDemoBundle:Manager');
$managers = $repo->findAll();
return $this->render('AcmeDemoBundle:Manager:list.html.twig', array(
'managers' => $managers,
));
}
{% extend '::base.html.twig' %}
{% block body -%}
{% for manager in managers -%}
{{ manager.name }}
{% endfor %}
{% endblock %}
更多信息可以在 Symfony2 学说文档和模板文档中找到。
但是,RoR 使用活动记录来持久保存数据库中的读取信息。在Symfony2中没有"模型"。你可以使用任何你想要的东西。默认情况下,它使用Doctrine2,但也包括Propel。
您也可以使用自己喜欢的"模型"库。如果你正在寻找像PHP中的活动记录这样的东西,你会发现很多有用的库,你可以使用。