【问题标题】:Failed to insert multiple tags on Laravel在 Laravel 上插入多个标签失败
【发布时间】:2017-11-18 07:30:24
【问题描述】:

我想插入一个带有多个标签的 Post 记录,所以这是我在 Post@store 中的代码:

$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');
    }
}

【问题讨论】:

    标签: laravel laravel-5 many-to-many laravel-eloquent


    【解决方案1】:

    您需要在 Post 模型中返回调用 hasMany

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

    更新

    您应该使用belongsToMany 而不是hasMany

    【讨论】:

    • 现在我收到此错误“调用未定义的方法 Illuminate\Database\Query\Builder::attach()”
    • 应该是belongsToMany 而不是hasMany
    • 太好了,谢谢。你也可以用 belongsToMany 更新你的答案吗?我会选择它。
    猜你喜欢
    • 2013-11-11
    • 2014-01-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-01-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多