Laravel将db值增加2倍

时间:2020-08-15 06:43:02

标签: php mysql laravel

这是返回视图的函数

class CuboidCreateAPIView(generics.CreateAPIView):
    model = Cuboid
    queryset = Cuboid.objects.all()
    serializer_class = CuboidCreateSerializers
    permission_classes = [IsStaff]



我想要的是在有人访问该页面时将值更新1,该帖子在其他页面的列表视图中,用户应该单击该链接。 一切正常,但是即使我按 reload 按钮,也不会将值增加1,而是增加2。 我可以假设的是,页面两次被请求 或首先通过某种中间件加载。这就是为什么请求被发送两次的原因 。我该如何解决?

1 个答案:

答案 0 :(得分:0)

此类基本计数器无法满足您的需求。您可以做的就是为您的帖子视图创建迁移:

Schema::create("post_views", function(Blueprint $table)
    {
        $table->unsignedInteger("id");
        $table->unsignedInteger("id_post");
        $table->string("session_id");
        $table->string("user_id");
        $table->string("ip");
        $table->string("agent");
        $table->timestamps();
    });

接下来创建一个模型,该模型将为您处理视图

class PostsViews extends \Eloquent {

protected $table = 'posts_views';

public static function createViewLog($post) {
        $postsViews= new PostsViews();
        $postsViews->id_post = $post->id;
        $postsViews->titleslug = $post->titleslug;
        $postsViews->url = \Request::url();
        $postsViews->session_id = \Request::getSession()->getId();
        $postsViews->user_id = \Auth::user()->id;
        $postsViews->ip = \Request::getClientIp();
        $postsViews->agent = \Request::header('User-Agent');
        $postsViews->save();
}

现在在showPost函数()中使用它:

public function showPost($id){
$targetPost = Post::findorFail($id);
PostsViews::createViewLog($targetPost);
$post = [
    'post' => $targetPost,
    'related_posts' => Post::all()->sortByDesc("id")->take(2)
    ];
    return view('post_single', $post);
}

现在它将记录所有视图,但是您可以在需要时在用户代理,IP地址或会话上将其过滤掉。您也可以在记录视图时使用这种过滤器,以便每个查看者每个帖子仅记录1个视图。