【发布时间】:2014-07-20 00:20:40
【问题描述】:
我建立了以下关系:
class Page {
public function comments() {
return $this->hasMany('Comment');
}
}
class Comment {
public function page() {
return $this->belongsTo('Page');
}
}
非常标准。一页可以有多个cmet,一条评论属于一页。
我希望能够创建一个新页面:
$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,但他们没有提到附加到一对多的一侧。甚至可能吗? (我觉得应该是)
【问题讨论】:
标签: laravel laravel-4 eloquent relationship