我喜欢帖子时执行的代码
// 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();
来自docs attach
和detach
函数用于多对多关系。使用save
进行一对多关系
oneToMany你应该使用Associate和dissociate。
ManyToMany你应该使用附加和分离。
所以你需要的是将同事改为附加,就是这样。
并且在使用之后你需要保存。
查看文档OneToMany和ManyToMany。