【问题标题】:How to join two table in symfony 5?如何在 symfony 5 中加入两个表?
【发布时间】:2021-06-25 19:22:45
【问题描述】:

我是 Symfony 的初学者,这是我的问题。

更准确地说,我的数据库中有两个表。第一个称为“post”,另一个称为“article”。 post表是article的父实体,这意味着article实体继承自post实体。我想要的是加入这两个表以从我的数据库中获取数据。

但是,在阅读了关于映射继承的学说和 symfony 文档后,我仍然无法解决我的问题。

你能帮我解决这个问题吗?

注意:这是我的代码

文章分类:

<?php

namespace App\Entity;

use Doctrine\ORM\Mapping as ORM;

/**
 * Articles
 *
 * @ORM\Table(name="articles")
 * @ORM\Entity(repositoryClass="App\Repository\ArticlesRepository")
 */
class Articles
{
    /**
     * @var int
     *
     * @ORM\Column(name="id", type="integer", nullable=false)
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="IDENTITY")
     */
    private $id;

    /**
     * @var int
     *
     * @ORM\Column(name="post", type="integer", nullable=false )
     * @ORM\GeneratedValue(strategy="IDENTITY")
     */
    private $post;

    /**
     * @ORM\Column(type="string", length=255)
     */
    private $themes;

    /**
     * Articles constructor.
     * @param int $post
     */

    public static $themeAvailable = [
        0 => "Environnement",
        1 => "Economie",
        2 => "Science et technologie",
        3 => "Loisir",
        4 => "Culture générale",
        5 => "Art",
        6 => "Sport"
    ];

    public function getId(): ?int
    {
        return $this->id;
    }

    public function getPost(): ?int
    {
        return $this->post;
    }

    public function getThemes(): ?string
    {
        return $this->themes;
    }

    public function setThemes(string $themes): self
    {
        $this->themes = $themes;

        return $this;
    }

    public function setPost(int $post)
    {
        $this->post = $post;
    }


}

发布类:

<?php

namespace App\Entity;

use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Validator\Constraints as Assert;

/**
 * Posts
 *
 * @ORM\Table(name="posts")
 * @ORM\Entity(repositoryClass="App\Repository\PostsRepository")
 */
class Posts
{
    /**
     * @var int
     *
     * @ORM\Column(name="id", type="integer", nullable=false)
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="IDENTITY")
     */
    private $id;

    /**
     * @var int
     *
     * @ORM\Column(name="author", type="integer", nullable=false)
     * @ORM\GeneratedValue(strategy="IDENTITY")
     */
    private $author;

    /**
     * @var string
     * @Assert\NotBlank()
     * @ORM\Column(name="title", type="string", length=255, nullable=false)
     */
    private $title;

    /**
     * @var string
     * @Assert\NotBlank()
     * @ORM\Column(name="content", type="text", length=65535, nullable=false)
     */
    private $content;

    /**
     * @var string
     * @Assert\File(
     *     maxSize = "20M",
     *     maxSizeMessage = "La taille du fichier trop importante. Minimum autorisé : 20 Mo.",
     *     mimeTypes = {"image/svg","image/png", "image/jpg", "image/jpeg", "image/gif" },
     *     mimeTypesMessage = "Format du fichier incorrecte. Formats autorisés : svg, png, jpg, jpeg, gif.",
     *     disallowEmptyMessage = "Veuillez importer une image supérieur à 0 Mo."
     *     )
     * @ORM\Column(name="image", type="blob", length=65535, nullable=false)
     */
    private $image;

    /**
     * @var \DateTime
     *
     * @ORM\Column(name="creation_date", type="datetime", nullable=false, options={"default"="CURRENT_TIMESTAMP"})
     */
    private $creationDate;

    /**
     * Posts constructor.
     */
    public function __construct()
    {
        $this->creationDate = new \DateTime();
    }


    public function getId(): ?int
    {
        return $this->id;
    }

    public function getAuthor(): ?int
    {
        return $this->author;
    }

    public function getTitle(): ?string
    {
        return $this->title;
    }

    public function setTitle(string $title): self
    {
        $this->title = $title;

        return $this;
    }

    public function getContent(): ?string
    {
        return $this->content;
    }

    public function setContent(string $content): self
    {
        $this->content = $content;

        return $this;
    }

    public function getImage(): string
    {
        return $this->image;
    }

    public function setImage($image): self
    {
        $this->image = $image;

        return $this;
    }

    public function getCreationDate(): ?\DateTimeInterface
    {
        return $this->creationDate;
    }

    public function setCreationDate(\DateTimeInterface $creationDate): self
    {
        $this->creationDate = $creationDate;

        return $this;
    }

    public function setAuthor(int $author)
    {
        $this->author = $author;
    }


}

我的仓库:

public function findAllArticle()
{
    return $this->createQueryBuilder('a')
        ->join('a.post',
            'p')
        ->addSelect('p')
        ->getQuery()
        ->getResult();
}

这是我的控制器:

<?php


namespace App\Controller;


use App\Entity\Articles;
use App\Entity\Posts;
use App\Form\PostsArticleType;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Annotation\Route;

class PostArticleController extends \Symfony\Bundle\FrameworkBundle\Controller\AbstractController
{
    /**
     * @var EntityManagerInterface
     */
    private $em;

    /**
     * ArticleController constructor.
     * @param EntityManagerInterface $em
     */
    public function __construct(EntityManagerInterface $em)
    {
        $this->em = $em;
    }

    /**
     * @Route("/post/create", name="index")
     * @return Response
     */

    public function index(): Response
    {
        return $this->render('post/index.html.twig');
    }

    /**
     * @Route("/post/article/show", name="showArticle")
     * @return Response
     */
    public function show(): Response
    {
        $articles = $this->getDoctrine()
            ->getManager()
            ->getRepository(Articles::class)
            ->findAllArticle();
        return $this->render('post/showArticle.html.twig', array('article' => $articles));
    }

    /**
     * @Route("/post/article/new", name="newArticle")
     * @param Request $request
     * @return Response
     */
    public function new(Request $request): Response
    {
        $post = new Posts();
        $article = new Articles();
        $post->setAuthor(1);
        $form = $this->createForm(PostsArticleType::class, $post);
        $form->handleRequest($request);

        if ($form->isSubmitted() && $form->isValid())
        {
            $this->em->persist($post);
            $this->em->flush();
            $article->setPost($post->getId());
            $themes = $form->get('themes')->getData();
            $article->setThemes(implode(',', $themes));
            $this->em->persist($article);
            $this->em->flush();

            return $this->redirectToRoute('home.html.twig');
        }

        return $this->render('post/CreateArticle.html.twig', ['form' => $form->createView()]);
    }
}

【问题讨论】:

    标签: php mysql symfony join doctrine-orm


    【解决方案1】:

    由于您有两个表帖子和文章,您可以使用“JOINED”继承: Posts 类应如下所示:

    /*...*/
    /**
     * Posts
     *
     * @ORM\Table(name="posts")
     * @ORM\Entity(repositoryClass="App\Repository\PostsRepository")
     *
     * @ORM\InheritanceType("JOINED")
     * @ORM\DiscriminatorColumn(name="discr", type="string")
     * @ORM\DiscriminatorMap({"posts" = "Posts", "articles" = "Articles"})
     */
    class Posts
    {
        /*...*/
    }
    

    对于文章类:

    /*...*/
    /**
     * Articles
     *
     * @ORM\Table(name="articles")
     * @ORM\Entity(repositoryClass="App\Repository\ArticlesRepository")
     */
    class Articles extends Posts
    {
        /*...*/
    }
    
    • 对于 posts 表,您将拥有 Posts 类属性,并在 DiscriminatorColumn 参数中配置一个名为“discr”的列(请参阅 Posts 类)。

    • 对于articles 表,您将拥有Articles 类属性和'posts_id' 列,它是一个外键(它引用'posts' 表的'id' 列)。

    有一些有用的链接:

    Doctrine : Class Table Inheritance

    About Doctrine inheritance - 部分:类表继承

    【讨论】:

    • ty 为您的解决方案,但我想知道我必须在我的 ArticleRepository 中写什么来获取只有文章类型而不是其他类型的帖子?
    • 尝试: public function findAllArticle() { return $this->createQueryBuilder('a')->getQuery()->getResult(); } 在 ArticlesRepository 类中。
    • 你的答案是Ty
    猜你喜欢
    • 2017-10-27
    • 2016-11-16
    • 2018-12-17
    • 2015-04-28
    • 2021-07-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多