简体   繁体   中英

How to associate objects of one-to-many relationships?

I'm using symfony 1.4 with Doctrine ORM. I have two classes related by a one-to-many relationship, and I have the object of the " one side ". I need to associate this object , let's say A, to the " many side " object, let's say B. The thing is A have not a method to add just one object to its Doctrine_Collection property, but instead it has a setter that receives a Doctrine_Collection. How can I achieve this association?

I have something like:

$a = new A();

$b = new B(); // Obviously, $b is not new, this is just for reference

$a->setB($b); // This is what I can't do. A::setB() receives a 
              // Doctrine_Collection of objects of type B, and I don't
              // know how to build it.

Please, any help would be really appreciated!!! thanks!

EDIT:

Maybe I didn't explained me well. My relationships are properly setted. I'm not trying to retrieve any object; instead, I'm trying to set the object. The problem is that the method A::setB() expects a Doctrine_Collection as a parameter, instead of the object itself. I don't know how to build that Doctrine_Collection , and that's what I'm asking here... I just need to add $b to the Doctrine_Collection of the related objects of $a .

If you need to just build a Doctrine_Collection , you can do so as follows:

// here, 'B' is the type of objects in the collection
$collection = new Doctrine_Collection("B");
$collection->add($b);

$a->setB($collection);

You can also do:

$a->b[] = $b;

and, as far as I know, Doctrine will add the relationship if it doesn't already exist, and ignore it if it does.

I feel like this should be possible in a way to similar to what you are describing, but I never had to. First, let me just state how I understand your question: You have a one to many relationship between 2 models. To make this easier to read, I will call the one side Categories and the many Posts. You want the be able to assign a doctrine collection of posts to the category by a function call, like $category->add($posts).

Most people end up doing this from the many side, and not the one side. That is, we are used to using $post->setCategory($category).

Personally, I would just look through the posts and assign category to each one. If you find the need to do this in a few places, you should probably make a custom function in your category class to handle this.

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