【问题标题】:Select from table where row equal to option symfony2从表中选择行等于选项 symfony2
【发布时间】:2016-01-26 08:22:52
【问题描述】:

我有一个由 symfony2 中的 crud 生成的表。该实体称为“Voorraad”(=Stock),是一个包含 3 个项目的表:“aantal”(=number)、“locatie_id”(location_id) 和“product_id”。位置 ID 和产品 ID 都是与另一个实体(位置实体和产品实体)的关联。我尝试按位置订购我的库存,但我无法在 symfony 中正确处理。我想有一个选择位置(id 1、id 2、id 3)的选项,如果选择了一个选项,它会输出该位置的数据。

在 mysql 中它的以下查询

SELECT * FROM `voorraad` WHERE `locatie_id` = 1

如何在 Symfony2/doctrine/twig 中实现这样的功能?

我的代码:

查看

{% extends '::base.html.twig' %}

{% block body -%}
<h1 class="hoofdtitel">Voorraad lijst</h1>
<table class="records_list">
    <thead>
        <tr>
            <!-- <th>Id</th> -->
            <th>Product</th>
            <th>Type</th>
            <th>Fabriek</th>
            <th>Aantal</th>
            <th>Inkoopprijs</th>
            <th>Verkoopprijs
            <th>Locatie</th>
            <th>Actions</th>
        </tr>
    </thead>
    <tbody>
    {% for entity in entities %}
        <tr>
    <!--    <td><a href="{{ path('voorraad_show', { 'id': entity.id }) }}">{{ entity.id }}</a></td> -->
            <td>{{ entity.getProduct().getNaam() }}</td>
            <td>{{ entity.getProduct().getType() }}</td>
            <td>{{ entity.getProduct().getFabric().getFabrieknaam() }}</td>
            <td>{{ entity.aantal }}</td>
            <td>{{ entity.getProduct().getInkoopprijs() }}</td>
            <td>{{ entity.getProduct().getVerkoopprijs() }}</td>
            <td>{{ entity.getLocatie().getLocatienaam() }}</td>
            <td>

                    <a href="{{ path('voorraad_edit', { 'id': entity.id }) }}">Voorraad aanpassen</a>

            </td>
        </tr>
        {% if
                entity.aantal   == 1 %}
    <div class="alert alert-info" role="alert"> <p>Let op, voorraad van {{ entity.getProduct().getNaam() }} is 1 of minder </p></div>
        {% endif %}

        {% if
        entity.aantal   <= 0 %}
            <div class="alert alert-danger" role="alert"> <p>Let op, voorraad van {{ entity.getProduct().getNaam() }} is op </p></div>
        {% endif %}
    {% endfor %}
    </tbody>
</table>

        <br>
        <a href="{{ path('voorraad_new') }}">
            Nieuwe voorraad toevoegen   
        </a>

{% endblock %}

控制器

namespace ToolsForEver\VoorraadBundle\Controller;

use Symfony\Component\HttpFoundation\Request;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Method;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
use ToolsForEver\VoorraadBundle\Entity\Voorraad;
use ToolsForEver\VoorraadBundle\Form\VoorraadType;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Security;

/**
 * Voorraad controller.
 *
 * @Route("/voorraad")
 */
class VoorraadController extends Controller
{

/**
 * Lists all Voorraad entities.
 *
 * @Route("/", name="voorraad")
 * @Method("GET")
 * @Template()
 * @Security("has_role('ROLE_USER')")
 */
public function indexAction()
{
    $em = $this->getDoctrine()->getManager();

    $entities = $em->getRepository('ToolsForEverVoorraadBundle:Voorraad')->findBy(array(), array('locatie'=>'asc'));

    return array(
        'entities' => $entities,
    );
}
/**
 * Creates a new Voorraad entity.
 *
 * @Route("/", name="voorraad_create")
 * @Method("POST")
 * @Template("ToolsForEverVoorraadBundle:Voorraad:new.html.twig")
 */
public function createAction(Request $request)
{
    $entity = new Voorraad();
    $form = $this->createCreateForm($entity);
    $form->handleRequest($request);

    if ($form->isValid()) {
        $em = $this->getDoctrine()->getManager();
        $em->persist($entity);
        $em->flush();

        return $this->redirect($this->generateUrl('voorraad_show', array('id' => $entity->getId())));
    }

    return array(
        'entity' => $entity,
        'form'   => $form->createView(),
    );
}

/**
 * Creates a form to create a Voorraad entity.
 *
 * @param Voorraad $entity The entity
 *
 * @return \Symfony\Component\Form\Form The form
 */
private function createCreateForm(Voorraad $entity)
{
    $form = $this->createForm(new VoorraadType(), $entity, array(
        'action' => $this->generateUrl('voorraad_create'),
        'method' => 'POST',
    ));

    $form->add('submit', 'submit', array('label' => 'Create'));

    return $form;
}

/**
 * Displays a form to create a new Voorraad entity.
 *
 * @Route("/new", name="voorraad_new")
 * @Method("GET")
 * @Template()
 * @Security("has_role('ROLE_USER')")
 */
public function newAction()
{
    $entity = new Voorraad();
    $form   = $this->createCreateForm($entity);

    return array(
        'entity' => $entity,
        'form'   => $form->createView(),
    );
}

/**
 * Finds and displays a Voorraad entity.
 *
 * @Route("/{id}", name="voorraad_show")
 * @Method("GET")
 * @Template()
 */
public function showAction($id)
{
    $em = $this->getDoctrine()->getManager();

    $entity = $em->getRepository('ToolsForEverVoorraadBundle:Voorraad')->find($id);

    if (!$entity) {
        throw $this->createNotFoundException('Unable to find Voorraad entity.');
    }

    $deleteForm = $this->createDeleteForm($id);

    return array(
        'entity'      => $entity,
        'delete_form' => $deleteForm->createView(),
    );
}

/**
 * Displays a form to edit an existing Voorraad entity.
 *
 * @Route("/{id}/edit", name="voorraad_edit")
 * @Method("GET")
 * @Template()
 * @Security("has_role('ROLE_USER')")
 */
public function editAction($id)
{
    $em = $this->getDoctrine()->getManager();

    $entity = $em->getRepository('ToolsForEverVoorraadBundle:Voorraad')->find($id);

    if (!$entity) {
        throw $this->createNotFoundException('Unable to find Voorraad entity.');
    }

    $editForm = $this->createEditForm($entity);
    $deleteForm = $this->createDeleteForm($id);

    return array(
        'entity'      => $entity,
        'edit_form'   => $editForm->createView(),
        'delete_form' => $deleteForm->createView(),
    );
}

/**
* Creates a form to edit a Voorraad entity.
*
* @param Voorraad $entity The entity
*
* @return \Symfony\Component\Form\Form The form
*/
private function createEditForm(Voorraad $entity)
{
    $form = $this->createForm(new VoorraadType(), $entity, array(
        'action' => $this->generateUrl('voorraad_update', array('id' => $entity->getId())),
        'method' => 'PUT',
    ));

    $form->add('submit', 'submit', array('label' => 'Update'));

    return $form;
}
/**
 * Edits an existing Voorraad entity.
 *
 * @Route("/{id}", name="voorraad_update")
 * @Method("PUT")
 * @Template("ToolsForEverVoorraadBundle:Voorraad:edit.html.twig")
 */
public function updateAction(Request $request, $id)
{
    $em = $this->getDoctrine()->getManager();

    $entity = $em->getRepository('ToolsForEverVoorraadBundle:Voorraad')->find($id);

    if (!$entity) {
        throw $this->createNotFoundException('Unable to find Voorraad entity.');
    }

    $deleteForm = $this->createDeleteForm($id);
    $editForm = $this->createEditForm($entity);
    $editForm->handleRequest($request);

    if ($editForm->isValid()) {
        $em->flush();

        return $this->redirect($this->generateUrl('voorraad_edit', array('id' => $id)));
    }

    return array(
        'entity'      => $entity,
        'edit_form'   => $editForm->createView(),
        'delete_form' => $deleteForm->createView(),
    );
}
/**
 * Deletes a Voorraad entity.
 *
 * @Route("/{id}", name="voorraad_delete")
 * @Method("DELETE")
 */
public function deleteAction(Request $request, $id)
{
    $form = $this->createDeleteForm($id);
    $form->handleRequest($request);

    if ($form->isValid()) {
        $em = $this->getDoctrine()->getManager();
        $entity = $em->getRepository('ToolsForEverVoorraadBundle:Voorraad')->find($id);

        if (!$entity) {
            throw $this->createNotFoundException('Unable to find Voorraad entity.');
        }

        $em->remove($entity);
        $em->flush();
    }

    return $this->redirect($this->generateUrl('voorraad'));
}

/**
 * Creates a form to delete a Voorraad entity by id.
 *
 * @param mixed $id The entity id
 *
 * @return \Symfony\Component\Form\Form The form
 */
private function createDeleteForm($id)
{
    return $this->createFormBuilder()
        ->setAction($this->generateUrl('voorraad_delete', array('id' => $id)))
        ->setMethod('DELETE')
        ->add('submit', 'submit', array('label' => 'Verwijder voorraad'))
        ->getForm()
    ;
}
}

【问题讨论】:

标签: php mysql symfony doctrine twig


【解决方案1】:

你可以使用学说的 findBy 方法:

$entities = $em->getRepository('ToolsForEverVoorraadBundle:Voorraad')
               ->findBy(['locatie'=>$locatieId]);

【讨论】:

  • 这个更好。我不知道findBy 已经存在所以不需要重新发明轮子。
【解决方案2】:

您可以在控制器中为此目标创建一个方法。大致代码如下(但这完全取决于您的映射信息和属性名称)。

public function getVoorraadByLocatieId($locatieId)
    {
            $em = $this->getDoctrine()->getManager();

            $query = $em->createQuery(
                'SELECT v
                FROM ToolsForEverVoorraadBundle:Voorraad v               
                WHERE v.locatie = :l_id'
                )->setParameter('l_id', $locatieId);
            $result = $query->getResult();

            return $result; 
    }

在你的行动中,做:

$this->getVoorraadByLocatieId($locatieId);

有不同的方法可以达到相同的结果,比如创建一个服务并从控制器内部调用它(胖服务和瘦控制器是上帝的做法),或者创建一个自定义的存储库类,但想法是一样的(使用实体管理器和学说获取)。后一种方式的优点是代码组织/可读性。

【讨论】:

  • 最佳实践是将此方法定位在相关的 Repository 类中,而不是在控制器中。
  • @fito,我完全同意你的看法。 Glenn,请谷歌如何创建 Repository 类并将相同的逻辑放入其中
  • 谢谢 :),我已经解决了这个$entities = $em-&gt;getRepository('ToolsForEverVoorraadBundle:Voorraad') -&gt;findBy(['locatie'=&gt;2]); 的问题,而不是使用我为每个位置硬编码 id 的变量,因为在 symfony 中创建我自己的控制器/存储库是新的我。还是谢谢!!
  • @GlennGijsberts,很高兴你取得了进展。一步一步你将成为 Symfony2/Doctrine2 的专家。祝你有美好的一天
猜你喜欢
  • 2012-12-29
  • 1970-01-01
  • 1970-01-01
  • 2011-09-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多