【发布时间】:2018-02-11 10:05:14
【问题描述】:
我的 laravel 项目中有一个 FatalThrowableError - 在 null 上调用成员函数 sync()。调试器显示mi,就是这行代码
Post::findOrFail($post_id)->tags()->sync([1, 2, 3], false);
这一行的完整方法如下所示:
public function store(Request $request)
{
// validate a post data
$this->validate($request, [
'title' => 'required|min:3|max:240',
'body' => 'required|min:50',
'category' => 'required|integer',
]);
// store post in the database
$post_id = Post::Create([
'title' => $request->title,
'body' => $request->body,
])->id;
Post::findOrFail($post_id)->tags()->sync([1, 2, 3], false);
// rediect to posts.show pages
return Redirect::route('posts.show', $post_id);
}
我的帖子模型看起来像
class Post extends Model
{
protected $fillable = [ ... ];
public function category() {...}
public function tags()
{
$this->belongsToMany('App\Tag', 'post_tag', 'post_id', 'tag_id');
}
}
我的 Tag 模型看起来像
class Tag extends Model
{
protected $fillable = [ ... ];
public function posts()
{
return $this->belongsToMany('App\Post', 'post_tag', 'tag_id', 'post_id');
}
}
感谢您的分析!
【问题讨论】:
-
您的
tags()方法缺少return语句:return $this->belongsToMany('App\Tag', 'post_tag', 'post_id', 'tag_id');
标签: laravel eloquent fatal-error laravel-eloquent