我怎样才能让一个 table / entity with doctrine (Symfony) 留在腰部?

How can I left loin a table / entity with doctrine (Symfony)?

在 mySQL 这是我的 table pages:

id  unique_id    name      template     icon    slug
1   jc62368231   Felder                  2     fields

和我的 table icons:

id  name
1   adjust
2   anchor

在我的 Controller.php 中,我通过学说从 Pages 获取内容:

$pages = $this->getDoctrine()->getRepository(Pages::class)->findAll();

这是我的输出:

   array:1 [▼
      0 => Pages {#4930 ▼
        -id: 5
        -unique_id: "jc62368231"
        -name: "Felder"
        -template: ""
        -icon: "2"
        -slug: "fields"
      }
    ]

我想做的是将 table icons 加入 pages table。要达到这个结果:

      array:1 [▼
      0 => Pages {#4930 ▼
        -id: 5
        -unique_id: "jc62368231"
        -name: "Felder"
        -template: ""
        -icon: "anchor"
        -slug: "fields"
      }
    ]

这是我的方法:

$pages = $this->getDoctrine()->getRepository(Pages::class)->join();

 /**
  * @return Pages[]
  */

  public function join('icons')
  {
    ->leftJoin('icons.id', 'icon')
    ->getQuery()
    ->getResult()
    ;
  }

但是我得到这个错误:

[Semantical Error] line 0, col 60 near 'icon': Error: Class App\Entity\Pages has no association named id

您的 join() 方法的内容毫无意义。您在不使用对象的情况下调用对象的方法。

连接不是以这种方式使用的。你必须使用 entityAlias.memberName

尝试这种方法,如果你想在你的控制器中使用它:

$pages = $this->getDoctrine()
              ->getRepository(Pages::class)
              ->createQueryBuilder('p') //Alias p for Page
              ->leftJoin('p.icon', 'i') //you are joining the icon member
              ->getQuery()
              ->getResult();

但我建议您改用 Repository class :

在/src/Repository/PagesRepository.php :

class PagesRepository extends EntityRepository
{
    public function GetIcons()
    {
        $query = $this->createQueryBuilder('p') //Alias p for Page
                      ->leftJoin('p.icon', 'i') //you are joining the icon member
                      ->getQuery()
                      ->getResult();

        return (query);
    }
}

在你的控制器中:

$pages = $this->getDoctrine()->getRepository(Pages::class)->GetIcons();

在您的实体中:

/*
 * @ORM\Entity(repositoryClass="App\Repository\PagesRepository")
 */
class Pages
{
    //Your entity
}

独特的页面有独特的图标。

一个图标可以有很多页。

从页面上下文来看,这是一个ManyToOne关系(许多页面可以有一个图标)

在你的实体Page中,图标的定义应该这样写:

/**
 * @var \Icons
 *
 * @ORM\ManyToOne(targetEntity="Icons")
 * @ORM\JoinColumn(name="icon", referencedColumnName="id")
 */
private $icon;

有关详细信息,请查看 documentation