雄辩的关系 - 附加(但不保存)有许多 [英] Eloquent relations - attach (but don't save) to Has Many

查看:123
本文介绍了雄辩的关系 - 附加(但不保存)有许多的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我设置了以下关系:

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;

和评论

$comment = new Comment;

并将评论附加到页面而不保存任何 / p>

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

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

我尝试过以下操作:

// 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)

推荐答案

听起来你只是想添加新的评论对象到页面的评论集 - 您可以轻松地使用基本的colection add方法:

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);

这篇关于雄辩的关系 - 附加(但不保存)有许多的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆