简体   繁体   中英

Undefined index when accessing OneToMany relationship in doctrine entity

I have the following entities structure for my tables: https://gist.github.com/melokki/e2e0d7c03ee71c37c1185602562da6af

$movie = $repository->findOneBy([
    'title' => 'movie title',
]);

I am trying to access a movie sources like this:

$movie->getSources()

and based on the documentation I can do it, but right now I am getting the following notice

Notice: Undefined index: movie

and I cannot understand why

Is it something wrong with my code?

I've run the doctrine:schema:validate command and now I think I got it.

My problem is that in MovieSchema for $movie property I have two annotations for the field: @ORM\\Column(type="string", name="movie_id") and @ORM\\JoinColumn(name="movie_id", referencedColumnName="id", nullable=false) .

I've removed the first one and now I get the desired result when I call the getSources method.

Thank you very much all for your time.

Based on your github link for your entities:

First

You can't do $movie->getSources() since there is no field called $sources in your Movie class

Second

In your movie-entity there is a field called $movieSource which is an one-to-many relation. That should be renamed to $movieSources cause you'll get back a ArrayCollection of MovieSource-objects

I suspect, you want to model a ManyToMany relation with Movie <-> Source?

If yes, you can directly link these entities to each other without being worry about an intermediate table, doctrine will do that for you.

See here: https://www.doctrine-project.org/projects/doctrine-orm/en/2.6/reference/association-mapping.html#many-to-many-bidirectional

I would strongly recommend to discard the intermediate table if there is no real usage for it.

But if you want to keep this model you'll have to call (after changing the methods name)

$movie->getMovieSources() 

and iterate over this collection.

for ($movie->getMovieSources() as $movieSource) {
  $moviesource->getSource();
}

It's most likely, that your original asked error is gone with these changes.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM