2017-09-02 116 views
1

我在我的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'); 
    } 
} 

謝謝你的激情!

+0

你'標籤()'方法缺少'return'聲明: '返回$這個 - > belongsToMany( '應用程序\標籤', 'post_tag', 'POST_ID', 'TAG_ID'); ' – bradforbes

回答

0

嘗試,你空對象,這意味着你的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); 
+0

謝謝你的激光,但這不能解決我的問題。我有這個相同的錯誤。在我累了之後:
'$ post = new Post;
$ post-> title = $ request-> title;
$ post-> body = $ request-> body;
$ post-> save();
$ post-> tags() - > sync([1,2,3],false); '

+0

你能否在帖子表中插入新帖?以及爲什麼你使用[1,2,3]而不是$ request-> tags .. –

+0

是的,我正確地創建一個新的張貼這張表。我使用[1,2,3],因爲這是簡單的測試數組,在致命錯誤 –

0

的錯誤狀態。

如果你看看你的tags()方法,你可以看到你忘了return的關係,因此它返回null。添加return關鍵字,你應該很好。

public function tags() 
{ 
    return $this->belongsToMany('App\Tag', 'post_tag', 'post_id', 'tag_id'); 
} 
相關問題