【问题标题】:Column name `id` referenced for relation from App\Entity\Students towards App\Entity\Classes does not exist从 App\Entity\Students 到 App\Entity\Classes 的关系引用的列名“id”不存在
【发布时间】:2020-08-14 23:10:23
【问题描述】:

在我的代码中,一个班级有很多学生。每个学生只有一个班级。

我正在尝试使用 php bin/console doctrine:schema:update --force 更新我的数据库架构 但我一直收到同样的错误:

列名 id 为来自 App\Entity\Students 的关系引用 对 App\Entity\Classes 不存在。

我该如何解决?

学生班:

<?php

namespace App\Entity;

use App\Repository\StudentsRepository;
use Doctrine\ORM\Mapping as ORM;

/**
 * @ORM\Entity(repositoryClass=StudentsRepository::class)
 */
class Students
{

    /**
     * @ORM\id()
     * @ORM\GeneratedValue()
     * @ORM\Column(type="integer")
     */
    private $studentID;

    /**
     * @ORM\ManyToOne(targetEntity="App\Entity\Classes", inversedBy="students")
     */
    private $classe;
   
  
    public function getclasse(): ?Classes
    {
        return $this->classe;
    }
    public function setclasse(?Classes $classe): self
    {
        $this->classes = $classe; 

        return $this;
    }

    
    public function getstudentID(): ?int
    {
        return $this->studentID;
    }

}

类类:

<?php

namespace App\Entity;

use App\Repository\ClassesRepository;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\Common\Collections\Collection;
use Doctrine\ORM\Mapping as ORM;

/**
 * @ORM\Entity(repositoryClass=ClassesRepository::class)
 */
class Classes
{
     /**
     * @ORM\Id()
     * @ORM\GeneratedValue()
     * @ORM\Column(type="integer")
     */
    private $classID;

    /**
      * @ORM\OneToMany(targetEntity="App\Entity\Students", mappedBy="classe")
      */
      private $students;

     public function __construct()
     {
         $this->students = new ArrayCollection();
     }

     /**
      * @return Collection/Students[]
      */
      public function getstudents(): Collection
      {
          return $this->students;
      }

【问题讨论】:

    标签: php database symfony doctrine


    【解决方案1】:

    我不熟悉教义,但看起来您正在尝试建立双向关系。 According to the docs, for a bidirectional one-to-many relationship:

    这种双向映射需要一侧的 mappedBy 属性和多侧的 inversedBy 属性。

    
    class Students {
        /**
         *
         * @ManyToOne(targetEntitity="App\Entity\Classes", mappedBy="students")
         * @JoinColumn(name="class_id", referencedColumnName="class_id")
         */
        private $classes;
    }
    
    class Classes {
       /**
         * @OneToMany(targetEntitity="App\Entity\Students", mappedBy="classes")
         */
        private $students;
    }
    
    
    

    注意学生的@joinColumn。我相信您通过在学生班级指定$studentID 和在班级班级指定$classID 来更改默认主键。因此,您必须指定要加入的列。


    以下内容是固执己见,所以持保留态度...

    FWIW,我建议使用默认主键,这通常是人们所做的(我会说这是行业标准/预期,但我相信人们不同意)。

    此外,根据您的实体名称,我预计它是多对多关系;但是,我不知道您的具体规格。

    【讨论】:

      猜你喜欢
      • 2022-01-08
      • 2019-08-23
      • 1970-01-01
      • 1970-01-01
      • 2019-08-17
      • 2019-08-10
      • 2021-10-02
      • 1970-01-01
      • 2021-07-24
      相关资源
      最近更新 更多