Laravel,调用成员函数sync()null
我在我的laravel项目中有一个FatalThrowableError - 调用null的成员函数sync()。 Debuger显示英里,也就是这行代码Laravel,调用成员函数sync()null
Post::findOrFail($post_id)->tags()->sync([1, 2, 3], false);
Complete方法这一行看起来像:
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');
}
}
谢谢你的激情!
尝试,你空对象,这意味着你的tags()
方法的结果是null
上调用sync()
这个
// store post in the database
$post = new Post([
'title' => $request->title,
'body' => $request->body,
]);
$post->save();
$post->tags()->sync([1, 2, 3], false);
谢谢你的激光,但这不能解决我的问题。我有这个相同的错误。在我累了之后:
'$ post = new Post;
$ post-> title = $ request-> title;
$ post-> body = $ request-> body;
$ post-> save();
$ post-> tags() - > sync([1,2,3],false); '
–
你能否在帖子表中插入新帖?以及为什么你使用[1,2,3]而不是$ request-> tags .. –
是的,我正确地创建一个新的张贴这张表。我使用[1,2,3],因为这是简单的测试数组,在致命错误 –
的错误状态。
如果你看看你的tags()
方法,你可以看到你忘了return
的关系,因此它返回null
。添加return
关键字,你应该很好。
public function tags()
{
return $this->belongsToMany('App\Tag', 'post_tag', 'post_id', 'tag_id');
}
你'标签()'方法缺少'return'声明: '返回$这个 - > belongsToMany( '应用程序\标签', 'post_tag', 'POST_ID', 'TAG_ID'); ' – bradforbes