我可以为不存在的表字段创建一个mutator吗?

时间:2013-08-21 16:29:44

标签: php laravel laravel-4 setter eloquent

问题

在Laravel 4中,我说有2个模型PostComment具有一对多的关系。我希望能够......

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,但这似乎不起作用。

任何帮助都非常感激。

1 个答案:

答案 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