保存功能在Eloquent中不起作用,

问题描述 投票:0回答:2

我喜欢帖子时执行的代码

   // auth()->id() is the id of the user that liked the post
   $post->post_likes()->associate(auth()->id());
   $post->save();

代码运行后发生错误

方法Illuminate \ Database \ Query \ Builder :: associate不存在。

-

发布模型

class Post extends Model
{

    public function post_likes()
    {            
        return $this->hasMany(PostLike::Class);
    }

}

更新

我喜欢这样做。

$post_like =  PostLike::create([
     'post_id' => $post->id,
     'user_id' => auth()->id()
]);

$post->post_likes()->save($post_like);            

现在我无法移除之类的东西。当我不喜欢帖子时,下面的代码会被执行。发生的错误是:

方法Illuminate \ Database \ Eloquent \ Collection :: dissociate不存在。

$post->post_likes->dissociate();

$post->save();
laravel laravel-5 laravel-5.2
2个回答
0
投票

来自docs attachdetach函数用于多对多关系。使用save进行一对多关系


0
投票

oneToMany你应该使用Associate和dissociate。

ManyToMany你应该使用附加和分离。

所以你需要的是将同事改为附加,就是这样。

并且在使用之后你需要保存。

查看文档OneToManyManyToMany

© www.soinside.com 2019 - 2024. All rights reserved.