gpt4 book ai didi

laravel - Eloquent 关系 - 附加(但不保存)到 Has Many

转载 作者:行者123 更新时间:2023-12-03 02:46:36 26 4
gpt4 key购买 nike

我建立了以下关系:

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

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

相当沼泽标准。一个页面可以有多个评论,一个评论属于一个页面。

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

$page = new Page;

和评论

$comment = new Comment;

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

$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

真正奇怪的是,相反的操作(将页面附加到评论)却可以正常工作:

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

相关文档为here但他们没有提到附加到一对多的一侧。有可能吗? (我感觉应该是这样)

最佳答案

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

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

关于laravel - Eloquent 关系 - 附加(但不保存)到 Has Many,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23951222/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com