【问题标题】:How to check if some post is liked by User in laravel如何在laravel中检查用户是否喜欢某些帖子
【发布时间】:2017-10-08 11:21:16
【问题描述】:

我有postsusersfavorites 表。 例如,我为 id 为 3 的用户制作了一些帖子,如下所示:

User::find(3)->favorites()->attach($post->id);

如果用户发送请求两次,它将使用post_iduser_id 插入此收藏夹两次。 我想检查该用户是否不喜欢某个帖子,然后将记录保存在数据库中。 或者如果一个帖子被收藏然后取消收藏。 我怎么能用雄辩的关系做到这一点? 我有UserPost 模型。

【问题讨论】:

标签: php laravel eloquent


【解决方案1】:

你可以使用toggle():

User::find(3)->favorites()->toggle($post->id);

如果它不喜欢它会喜欢它,如果它不喜欢它就会不喜欢它。

如果你只是想让函数在表格中不重复点赞,只需使用syncWithoutDetaching

User::find(3)->favorites()->syncWithoutDetaching([$post->id]);

把它放在你的用户模型上:

class User extends Model {

  public function like($postId){
    $this->favorites()->syncWithoutDetaching([$post->id]);
  }

  public function unlike($postId){
    $this->favorites()->detach([$post->id]);
  }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-10-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多