Laravel Method sync does not exist

2019-08-26 22:44发布

问题:

Post Model

<?php

namespace App\Model\User;

use Illuminate\Database\Eloquent\Model;

class Post extends Model
{
   public function tags(){
     return $this->belongsToMany('App\Model\User\Tag','post__tags', 'post_id', 'tag_id');
  }

  public function categories() {
     return $this->belongsToMany('App\Model\User\Category','category__posts','post_id', 'category_id');
  }
}

Category Model

<?php

namespace App\Model\User;
use Illuminate\Database\Eloquent\Model;

class Category extends Model
{
   public function posts(){
      return $this->belongsToMany('App\Model\User\Category','category__posts', 'post_id', 'category_id');
   }

}

Tag Model

<?php

namespace App\Model\User;

use Illuminate\Database\Eloquent\Model;

class Tag extends Model
{
   public function posts() {
       return $this->belongsToMany('App\Model\User\Post','post__tags','post_id','tag_id');
   }
}

PostController.php

public funcion store()
{
// do validation here
   try{
      $post = new Post;
      $post->title = $request->title;
      $post->subtitle  =  $request->subtitle;
      $post->slug  =  $request->slug;
      $post->body  =  $request->body;           
      $post->status  =  1;                   
      $post->save();     // This works correct 
      $post->tags->sync($request->tags); // Not working
      $post->categories->sync($request->categories);  // Not working
   }
   catch(\Exception $e){ 
      return redirect(route('post.index'))->with('message', 'Error Adding Post into system!'.$e->getMessage()); // getting Message "Method sync does not exist. "
    }      
}

回答1:

Sync is a method on the builder instance, you're using it on the collection.

 // change your code like this
 $post->tags()->sync($request->tags);
 $post->categories()->sync($request->categories);


回答2:

You need to use the following:

$post->tags()->sync($request->tags);
$post->categories()->sync($request->categories);

Don't forget the () in tags and categories

$post->categories without () is a Collection instance.

$post->categories() is a belongsToMany instance