我在我的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');
}
}
謝謝你的激情!
你'標籤()'方法缺少'return'聲明: '返回$這個 - > belongsToMany( '應用程序\標籤', 'post_tag', 'POST_ID', 'TAG_ID'); ' – bradforbes