1

Zend Framework 3, Doctrine 2. I created some mapping of 2 tables MySQL

/**
* @ORM\Entity
* @ORM\Table(name="object")
*/
class Object 
{
    /**
    * @ORM\Id
    * @ORM\GeneratedValue
    * @ORM\Column(name="id")
    */
    protected $id;

   /**
    * @ORM\OneToOne(targetEntity="..\Host", inversedBy="object")
    * @ORM\JoinColumn(name="ip", referencedColumnName="IP")
    */
   protected $host;

}

/**
 * @ORM\Entity
 * @ORM\Table(name="host")
 */
class Host 
{
    /**
     * @ORM\Id
     * @ORM\Column(name="IP")
    */
    protected $ip;


    /**
     * @ORM\OneToOne(targetEntity="..\Object", mappedBy="host")
     * @ORM\JoinColumn(name="IP", referencedColumnName="ip")
     */
    protected $object;
}

I have this error:

Error "Missing value for primary key id on ..\Object".

Why? It seems to be done according to the example -> 5.3. One-To-One, Bidirectional from the site Doctrine

MoOgur
  • 23
  • 4

1 Answers1

0

The parameters you pass to JoinColumn are incorrect. You can check the doc for JoinColumn here.

Try like this:

// For Object class: 
// @ORM\JoinColumn(name="host_ip", referencedColumnName="ip")

// For Host class
// @ORM\JoinColumn(name="object_id", referencedColumnName="id")

In addition to this: mappedBy is not supported in OneToOne annotations. You can use targetEntity and inversedBy but not mappedBy.

On the other hand, making the ip your primary key seems wrong. You should have an auto-generated primary id for Host and use that to connect the entities. You can still set you ip field as unique, so you won't have duplicates. Plus you don't have any other fields, you can even just put the ip within Object class.

Also, I don't recommend using Object as your class name. It is too general.

gurel_kaynak
  • 546
  • 6
  • 11
  • I'll try this solution. Unfortunately, I can not edit the table, they are already created and used. And the fields are not all indicated, but only those that are used for mapping – MoOgur Nov 30 '17 at 14:15
  • If the tables were there before you started using doctrine, then first you can generate the entities with doctrine instead of creating classes manually. There's a howto here: https://samsonasik.wordpress.com/2013/04/10/zend-framework-2-generate-doctrine-entities-from-existing-database-using-doctrinemodule-and-doctrineormmodule/ – gurel_kaynak Nov 30 '17 at 14:55