我的 Laravel 项目中有一个 FatalThrowableError - 在 null 上调用成员函数 sync()。Debuger show 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);
}
我的 Post 模型看起来像
class Post extends Model
{
protected $fillable = [ ... ];
public function category() {...}
public function tags()
{
$this->belongsToMany('App\Tag', 'post_tag', 'post_id', 'tag_id');
}
}
我的标签模型看起来像
class Tag extends Model
{
protected $fillable = [ ... ];
public function posts()
{
return $this->belongsToMany('App\Post', 'post_tag', 'tag_id', 'post_id');
}
}
谢谢你的回答!
试试这个
// store post in the database
$post = new Post([
'title' => $request->title,
'body' => $request->body,
]);
$post->save();
$post->tags()->sync([1, 2, 3], false);
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句