A
A
Alexey Nikolaev2018-10-21 01:26:29
symfony
Alexey Nikolaev, 2018-10-21 01:26:29

Why doesn't the one-to-many relationship work?

Goodnight.
There is a `limits` table and a `limits_params` table.

Schemas of these tables
CREATE TABLE limits(
    id INT AUTO_INCREMENT NOT NULL,
    PRIMARY KEY(id)
) ENGINE = InnoDB;

CREATE TABLE limits_params(
    id INT AUTO_INCREMENT NOT NULL,
    limit_id INT DEFAULT NULL,
    PRIMARY KEY(id)
) ENGINE = InnoDB;
ALTER TABLE `limits_params` ADD CONSTRAINT fk_limit_id FOREIGN KEY (`limit_id`) REFERENCES `limits` (id)

There are corresponding entities Limits and LimitParams.
Open Code
/**
 * @ORM\Entity(repositoryClass="App\Repository\LimitsRepository")
 */
class Limits
{
    /**
     * @ORM\OneToMany(targetEntity="App\Entity\LimitParams", mappedBy="limit", cascade={"persist"})
     */
    private $params;

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

    public function getParams()
    {
        return $this->params;
    }
}

/**
 * @ORM\Entity(repositoryClass="App\Repository\LimitParamsRepository")
 * @ORM\Table(name="limits_params")
 */
class LimitParams
{
    /**
     * @ORM\ManyToOne(targetEntity="App\Entity\Limits", inversedBy="params", cascade={"persist"})
     * @ORM\JoinColumn(name="limit_id", referencedColumnName="id")
     */
    private $limit;
}

I did everything as in the textbook, by all logic it should work. But doesn't work, getParams always returns an empty collection. I tried to use JoinTable in the Limits entity in order to explicitly point to a table with $params, but that doesn't work either.
In this case, the database has all the records in both tables - the version "there are no records in the limits_params table" is excluded. Records are also normally created using setters in both entities.
What did I miss? Why does not it work?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
Denis, 2018-10-21
@Heian

The doctrine "lazily" loads collections. This means that the results will be only when explicitly accessed, that is, when iterating and accessing properties.
For "greedy" loading in the config (in your case, the annotation), you need to write eager = "fetch", then the collection will be initialized immediately

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question