简体   繁体   English

如何从该特定用户中删除“喜欢”?

[英]How do I remove the one "like" from that particular user?

Trying do create a "like system" for a simple application with Laravel and Livewire.尝试使用 Laravel 和 Livewire 为简单的应用程序创建一个“类似系统”。 I have managed to add likes, but I only want the user to be able to add one (1) like to a post.我设法添加了喜欢,但我只希望用户能够在帖子中添加一 (1) 个喜欢。 At the moment a user can add as many likes as he or she wants.目前,用户可以添加任意数量的喜欢。

This is my current function to store likes:这是我目前的 function 来存储喜欢:

    public function storeLike()
    {
        // Check if the user already has liked the post
        if($this->collection->likes()->exists()){
            return $this->collection->likes()->delete();
        }

        // If not, add one like to the db
        $like = $this->collection->likes()->make();
        $like->user()->associate(auth()->user());

        // Save the like
        $like->save();
    }

And the part that im struggling with is:我挣扎的部分是:

        if($this->collection->likes()->exists()){
            return $this->collection->likes()->delete();
        }

It deletes all the likes for that post.它会删除该帖子的所有喜欢。 So how can a disassociate, detach that like if it exists?那么,如果存在的话,如何分离,分离呢?

This is how I have made the collection:这就是我收集的方式:

        $collection = collect();

        $posts = Post::search('topic', $this->search)->with(['user'])->latest()->get();
        $urls = Urls::search('topic', $this->search)->with(['user'])->latest()->get();
        $news = News::search('topic', $this->search)->latest()->get();

        /** Push posts to the collection */
        foreach ($posts as $post) $collection->push($post);
        /** Push urls to the collection */
        foreach ($urls as $item) $collection->push($item);
        /** Push news to the collection */
        foreach ($news as $item) $collection->push($item);

I think the toggle (see docs ) method could be very handy.我认为toggle (参见文档)方法可能非常方便。

Let's assume we're building a component for a model called Post .假设我们正在为 model 构建一个名为Post的组件。

Livewire活线

public function clickedLike() {
    $this->post->likes()->toggle(Auth::user());
}

Template模板

<button wire:click="clickedLike">
    <3
</button>

Model Model

class Post extends Model {
    public function likes() {
        return $this->hasMany(User::class, 'likes')
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM