2017-11-18 128 views
0

插入多个标签,我想插入多个标签一个帖子记录,因此,这里是我的邮编@店:未能就Laravel

$post = Post::create(array(
      'title' => $request->title, 
      'body' => $request->body, 
      'user_id' => Auth::id(), 
     )); 

     if($post && $request->tags) 
     { 
      $tagNames = explode(',', $request->tags); 
      $tagIds = []; 
      foreach($tagNames as $tagName) 
      { 
       $tag = Tag::firstOrCreate(['name'=>$tagName]); 
       if($tag) 
       { 
        $tagIds[] = $tag->id; 
       } 
      } 

      $post->tags()->attach($tagIds); 
     } 

,但它给我一个错误"Call to a member function attach() on null"。当我在MySQL中检查标记已经在那里,但我无法找到我的post_tag表上的任何条目。这里是我的岗位模型:

class Post extends Model 
{ 
    protected $fillable = ['user_id','title','slug','body','tags','category_id','featured']; 

    public function category() 
    { 
     return $this->belongsTo('App\Category'); 
    } 

    public function tags() 
    { 
     $this->hasMany('App\Tag'); 
    } 
} 

回答

1

您需要在您的Post模型回电话的hasMany

public function tags() 
{ 
    return $this->hasMany('App\Tag'); 
} 

更新

您应该使用belongsToManyhasMany

+0

现在我得到了这个错误“调用未定义的方法照亮\数据库\查询\ Builder :: attach()” – Ying

+0

它应该是'belongsToMany'不'hasMany' – Hamoud

+0

伟大,谢谢。你能用belongsToMany更新你的答案吗?我会选择它。 – Ying