雄辩的关系 - 附加(但不保存)有很多

Joe*_*Joe 20 relationship laravel eloquent laravel-4

我建立了以下关系:

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

class Comment {
    public function page() {
        return $this->belongsTo('Page');
    }
}
Run Code Online (Sandbox Code Playgroud)

漂亮的沼泽标准.一个页面可以有很多注释,一个注释属于一个页面.

我希望能够创建一个新页面:

$page = new Page;
Run Code Online (Sandbox Code Playgroud)

和评论

$comment = new Comment;
Run Code Online (Sandbox Code Playgroud)

并将评论附加到页面,而不保存任何

$page->comments->associate($comment);
Run Code Online (Sandbox Code Playgroud)

我尝试过以下方法:

// 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
Run Code Online (Sandbox Code Playgroud)

真正奇怪的是,相反(将页面附加到注释)正常工作:

$comment->page()->associate($page);
Run Code Online (Sandbox Code Playgroud)

相关的文档在这里,但他们没有提到附加到一对多的ONE方面.它甚至可能吗?(我觉得应该是)

Ben*_*ird 27

听起来您只想将新的评论对象添加到页面的评论集合中 - 您可以使用基本的集合添加方法轻松完成:

$page = new Page;
$comment = new Comment;
$page->comments->add($comment);
Run Code Online (Sandbox Code Playgroud)

  • 完美,完全符合我的需要:)谢谢 (2认同)
  • 您还应该能够使用$ page-> push()来保存页面和所有相关注释,而不是单独保存每个注释. (2认同)

Jar*_*zyk 9

你不能这样做,因为没有要链接的ID.

首先,您需要保存父($page)然后保存子模型:

// $page is existing model, $comment don't need to be
$page->comments()->save($comment); // saves the comment
Run Code Online (Sandbox Code Playgroud)

或者相反,这次没有保存:

// again $page exists, $comment don't need to
$comment->page()->associate($page); // doesn't save the comment yet
$comment->save();
Run Code Online (Sandbox Code Playgroud)


Jul*_*att 5

根据 Benubird 的说法,我只是想添加一些东西,因为我今天偶然发现了这个:

您可以在像 Benubird 所述的集合上调用 add 方法。为了考虑 edpaaz(附加触发查询)的担忧,我这样做了:

$collection = $page->comments()->getEager(); // Will return the eager collection
$collection->add($comment) // Add comment to collection
Run Code Online (Sandbox Code Playgroud)

据我所知,这将阻止额外的查询,因为我们只使用关系对象。

在我的情况下,其中一个实体是持久的,而第一个(在您的案例页面中)不是(并且将被创建)。由于我必须处理一些事情并希望以对象方式处理它,因此我想将一个持久化实体对象添加到一个非持久化对象中。也应该与非持久性一起使用。

感谢 Benubird 为我指明了正确的方向。希望我的添加对某人有帮助,就像对我一样。

请记住,这是我的第一篇 stackoverflow 帖子,所以请留下您的反馈。