Jazi
Jazi

Reputation: 6712

Doctrine 2.1 - entity inserting

I have question about inserting entity into a database. I have two models:

class News {
    /**
     * @Column(type="string", length=100)
     * @var string
     */
    protected $title;

    /**
     * @ManyToOne(targetEntity="User", inversedBy="news")
     * @JoinColumn(referencedColumnName="id")
     */ 
    protected $author;

}

class User {
    /**
     * @Id @GeneratedValue @Column(type="integer")
     * @var integer
     */
    protected $id;

    /**
     * @OneToMany(targetEntity="News", mappedBy="author")
     */
    protected $news;

    public function __construct() {
        $this->news = new \Doctrine\Common\Collections\ArrayCollection;
    }

}

To add new news I must include both User and News classes (if they're in separate files, for ex. UserModel.php and NewsModel.php) and write a code:

$news = new News()
$news->setTitle('TEST title');
$news->setAuthor($database->find('User', 1));
$database->persist($news);

My question is: Is there any way to insert news without including User class?

Upvotes: 3

Views: 4781

Answers (2)

jere
jere

Reputation: 4304

one other thing you could do (thinking in a more object-oriented kinda way) is add a method called addNews($news) on your user entity:

public function addNews($news) {
    // you should check if the news doesn't already exist here first
    $this->news->add($news);
    $news->setAuthor($this);
}

and add cascade persist to your mapping:

/**
 * @OneToMany(targetEntity="News", mappedBy="author", cascade={"persist"})
 */
protected $news;

then fetch your user, add the news, and merge the changes:

$news = new News()
$news->setTitle('TEST title');    
$author = $database->find('User', 1);

$author->addNews($news);

//merge changes on author entity directly
$em->merge($author);

I preferr this approach because it gives you the opportunity to do extra checks or controls while adding the news, making for reusable and easy to read code

Upvotes: 1

timdev
timdev

Reputation: 62874

You don't need to actually load the User.

Instead, you can use a reference proxy:

<?PHP
$news = new News()
$news->setTitle('TEST title');
$news->setAuthor($em->getReference('User',1));
$em->persist($news);

Upvotes: 7

Related Questions