【问题标题】:Laravel How to store a variable into database and update it on every clickLaravel如何将变量存储到数据库中并在每次点击时更新它
【发布时间】:2018-06-29 06:33:43
【问题描述】:

我有 laravel 博客,我已经使用 Vue.js 实现了“添加到收藏夹”选项,并且效果很好。现在我想实现类似的帖子(每个用户都可以喜欢更多次),就像中等拍手一样,我已经有了拍手按钮并且它可以工作,每次点击 $likeCounter 变量都会更新并保持,问题是如何将该变量($likeCounter)插入数据库(使用 javascript、vuejs ...)?喜欢表有这些列 user_id、post_id、likes_count user_id & post_id (pivot) 使用 vue.js 插入

在我的控制器中,我有这个方法来附加 user_id 和 post_id

public function like(Post $post)
{
    Auth::user()->likes()->attach($post->id);

    return back();
}

在用户模型中,我有这种方法可以为经过身份验证的用户获取所有喜欢的帖子

/**
 * Get all of liked posts for the user.
 */
public function likes()
{
    return $this->belongsToMany(Post::class, 'likes', 'user_id', 'post_id')->withTimeStamps();
}

在 Post Model 中我有这个方法

/**
 * Determine whether a post has been liked by a user.
 *
 * @return boolean
 */
public function liked()
{
    return (bool) Like::where('user_id', Auth::id())
                        ->where('post_id', $this->id)
                        ->first();
}

public function likes()
{
    return $this->hasMany('App\Models\Like');
}

在 Like.vue 中

methods: {
        like(post) {
            axios.post('/like/'+post)
                .then(response => this.isLiked = true)
                .catch(response => console.log(response.data));
        },

我使用一些 javascript 在每次点击时更新一个变量,直到当前用户达到最大值,即每个经过身份验证的用户最多 50 次鼓掌

function updateNumberOfClaps() {
    numberOfClaps < 50 ? numberOfClaps++ : null
    clapCount.innerHTML = "+" + numberOfClaps
    clapTotalCount.innerHTML = initialNumberOfClaps + numberOfClaps
  }

而且效果很好(用 user_id 和 post_id 附加新的like),如果同一个用户再次点击同一个帖子,一个新的like 将附加到具有相同 user_id 和相同 post_id 的数据库中。 问题是我如何在 likes_count 列中存储变量计数器并在每次点击时更新它,所以我不想一次又一次地将同一个帖子与同一个用户附加,我想存储一个变量,说明有多少用户喜欢这个帖子。 我希望这很清楚

【问题讨论】:

  • 问题出在哪里,前端还是后端?
  • @Tpojka 后端,将变量存储到数据库并在每次点击时更新,变量使用javascript更新
  • 是否有限制用户可以点击一篇文章?
  • @Tpojka 只有经过身份验证的用户才能点赞按钮
  • 你说可以多次,但是一个用户一个帖子的数量有限制吗?

标签: javascript php laravel vue.js


【解决方案1】:

likes_count 的默认值设置为 50。然后,在您的更新方法中:

public function update(Request $request, $id)
{
    try {
        $userId = Auth::id();

        $like = Like::firstOrCreate([
            'user_id' => $userId,
            'post_id' => $id
        ]);

        if ((int)$like->likes_count < 1) {
            // user can not like this post anymore
            return response()->json(['message' => 'Like limit exceeded.']);
        }

        $like->decrement('likes_count');

        return response()->json(['message' => 'Post liked.']);

    } catch (\Exception $e) {
        Log::info('Something went wrong liking post ' . $id . ' by ' . $userId . ': ' . $e->getMessage());
        return response()->json(['message' => 'Error.']);
    }


}

不要忘记包含类(Request、Auth、App\Like、Log...)。

【讨论】:

  • “消息”“错误”
  • 包括 $e-&gt;getMessage() 而不是字符串“错误”。并检查你得到了什么。
  • 你得到了什么?
  • 没有响应显示,也没有任何东西插入数据库
  • 您收到“消息”“错误”。因为 try catch 块的 catch 部分被执行。这意味着在尝试部分没有任何评估,因此也没有数据库插入。如果你使用了准确的代码,storage/logs/laravel.log 文件中应该有一些内容。
【解决方案2】:

这是对我之前做过的项目的反应的实现。我将为您提供模型并在我的控制器中剥离逻辑以保存反应以帮助您解决问题。

这应该让您对表结构和处理它的控制器逻辑有一个很好的理解。

如果您想了解有关逻辑如何工作的更多详细信息,请询问。希望这会有所帮助。

模型 - 反应和反应类型。

反应表存储对事物的所有反应,它是一个数据透视表,用于存储

  • user_id - 对某事做出反应/点赞的用户
  • 相关表 - 用户喜欢的对象来自的表
  • related table id - 用户喜欢的内容的引用....这是我可以找到项目被喜欢的人的地方
  • reaction_type_id - 这是对反应类型的引用(参见反应类型)

ReactionType - 存储人们在您的应用中可能产生的反应类型:

  • 反应名称 - 用于标记反应的标签(喜欢、不喜欢、讨厌、喜欢等)
  • description - 反应含义的描述。
  • 图标 - 从视图中的图标/图像角度呈现的内容。

    class Reaction extends Model
    {
        protected $fillable = array('user_id', 'related_table', 'related_table_id', 'reaction_type_id');
        protected $table = 'reactions';
    }
    
    class ReactionType extends Model
    {
        protected $fillable = array('name', 'description', 'icon');
        protected $table = 'reaction_types';
    }
    

控制器 - 这是存储反应的内容 我在控制器中有注释来解释它。

class ReactionController extends Controller
{

    public function store(Requests\ReactionRequest $request)
    {
        $reaction = array(
            'user_id' => $request->id, 
            'reaction_type_id' => $request->reaction_type_id, 
            'related_table' => $request->related_table, 
            'related_table_id' => $request->related_table_id );
        //Check to see if there's a record already.  You can only have one reaction per item. 
        $CheckInDB = Reaction::where('user_id', '=', $reaction['user_id'])
    ->where('related_table', '=', $reaction['related_table'])
    ->where('related_table_id', '=', $reaction['related_table_id'])->first();
    //If the reaction is in the database then update the type (did they change reaction? 
    if ($CheckInDB) {
        //If they sent the same exact reaction type that is already in the database, then 0 it out... This would indicate they unselected the reaction they provided.
        if($CheckInDB->reaction_type_id == $reaction['reaction_type_id'])   {
            $CheckInDB->reaction_type_id = 0;   
        }
        //Otherwise, update the reaction_type_id with the new reaction.
        else {
            $CheckInDB->reaction_type_id = $reaction['reaction_type_id'];   
        }
        //Update the reaction.
        $CheckInDB->save();
    }
    //If the user has never reacted to the item, then create a new record with that reaction.
    else {
        Reaction::create($reaction);
    }
    return back();
}

}

【讨论】:

  • 感谢您的回复@Dom,这是一个很好的实现,但这不是我需要的,我想让用户喜欢发布更多次,我已经实现过一次并且它有效,我每次点击都会更新一个变量,比如 btn,我只想使用 vue js 存储该变量
  • 上述模型和控制器将存储特定帖子的喜欢,这似乎是您最初的问题。您能否提供一些有关您当前控制器或保存方法的详细信息以及为什么它不起作用?
  • 我已经更新了问题的更多细节,请看一下
  • @A.Bechir,谢谢,我刚刚阅读了您更新的问题。它缺少一个关键要素。您的存储方法(即您用来将点击存储到数据库的方法)是什么样的?如果你能给我存储控制器和 dd($request->all())。您提供的 like 方法实际上并没有更新数据库上的表。此外,您检索存储在数据库中的特定帖子的喜欢数量的对象是什么样的?
  • 我可以将我使用的所有代码和方法提供给您,但如果这里允许,我不会在帖子中添加整个代码
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-07-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-08-19
  • 2012-03-16
相关资源
最近更新 更多