Eloquent relations - attach (but don't save) to Has Many

Joe picture Joe · May 30, 2014 · Viewed 26.3k times · Source

I have the following relations set up:

class Page {
    public function comments() {
        return $this->hasMany('Comment');
    }
}

class Comment {
    public function page() {
        return $this->belongsTo('Page');
    }
}

Pretty bog standard. One page can have many comments, and one comment belongs to a single page.

I'd like to be able to create a new page:

$page = new Page;

and a comment

$comment = new Comment;

and attach the comment to the page, without saving any of it

$page->comments->associate($comment);

I've tried the following:

// These are for one-to-many from the MANY side (eg. $comment->page->associate...)
$page->comments->associate($comment);   // Call to undefined method Illuminate\Database\Eloquent\Collection::associate()
$page->comments()->associate($comment); // Call to undefined method Illuminate\Database\Query\Builder::associate()

// These 2 are for many-to-many relations, so don't work
$page->comments->attach($comment);      // Call to undefined method Illuminate\Database\Eloquent\Collection::attach()
$page->comments()->attach($comment);    // Call to undefined method Illuminate\Database\Query\Builder::attach()

// These 2 will (if successful) save to the DB, which I don't want
$page->comments->save($comment);        // Call to undefined method Illuminate\Database\Eloquent\Collection::save()
$page->comments()->save($comment);      // Integrity constraint violation: 1048 Column 'page_id' cannot be null

The really odd thing is that doing the opposite (attaching the page to the comment) works correctly:

$comment->page()->associate($page);

The relevant docs are here but they don't make any mention of attaching to the ONE side of a one-to-many. Is it even possible? (I feel like it should be)

Answer

Benubird picture Benubird · May 30, 2014

It sounds like you just want to add the new comment object to the page's comments collection - you can do that easily, using the basic colection add method:

$page = new Page;
$comment = new Comment;
$page->comments->add($comment);