如何检查是否已存在三列?

时间:2018-01-09 07:53:13

标签: php laravel laravel-eloquent

我尝试为多个模型创建通用评级系统。

例如,列表模型的方法:

    public function setRating(RatingRequest $request)
{
    $rating = Rating::firstOrCreate([
        'entity_id' => $request->entity_id,
        'entity_type' => Feed::class,
        'ip' => $request->ip,
        'rating' => $request->rating
    ]);

    if (!$rating->wasRecentlyCreated) {
        $feed = Feed::find($request->entity_id);
        $feed->update([
            'rating' => round(((($feed->rating * $feed->count_rating_votes) + $request->rating) / ++$feed->count_rating_votes) * 2) / 2,
            'count_rating_voted' => $feed->count_rating_votes,
        ]);
    }
}

如何检查具有某些IP的用户是否已为某些entity_type = 1和entity_id = 1投票?

如果没有添加记录并重新计算评级?

1 个答案:

答案 0 :(得分:0)

为实体投票创建一个表,并使用user_id外键将其与用户模型类型中的每个用户相关联:

public function votes()
{
return $this->hasMany(App\vote::class);
}

在投票模型类型中:

public function user()
    {
    return $this->belongsTo(App\user::class);
    }

现在您可以通过以下方式访问每个用户投票:

return user()->with('votes')->get();