在Laravel 4中,我说有2个模型Post
和Comment
具有一对多的关系。我希望能够......
Post::create(['post_title' => 'foo',
'comment' => ['text' => 'Some comment']);
...并为此创建帖子记录以及新评论记录。这是我的尝试: -
class Post extends Model {
// Make all field mutable
public static $unguarded = true;
// Create relationship
public function comments() {
return $this->hasMany('Comment');
}
// Setter for comment
public function setComment($comment) {
$this->comments()->create($comment);
return FALSE;
}
}
但我收到错误: -
Column not found: 1054 Unknown column 'comment' in 'field list'
是否有可能让Laravel不去寻找这个领域?我尝试从设置器中返回FALSE
,但这似乎不起作用。
任何帮助都非常感激。
答案 0 :(得分:1)
我没有测试过 - 但这应该有用;
class Post extends Model {
public function comments() {
return $this->hasMany('Comment');
}
public function createPostAndComment($post, $comment)
{
if ($this->create($post))
{
$this->comments()->save($comment);
}
}
}
你可以read more here。