Laravel 多对多关系计数

Laravel many to many relastionship count

我有两个 table。用户和天数,具有多对多的关系。 user_days : user_id, day_id

public function users()
{
    return $this->belongsToMany(User::class, 'user_day');
}

public function days()
{
    return $this->belongsToMany(Day::class, 'user_day');
}

我想获取 day_id = 1 {某天} 或类似信息的用户计数。有什么方法可以从 pivot table 获取计数? 此功能无效。

public function assign_prize(Request $request)
{
    $userCount = $this->user->days()->withCount('users')->where($request->day_id, 'day_id')->get();
    $giftLimit = Day::where('id', $request->day_id)->get();
    if ($userCount > $giftLimit) {
        return problem(__("Gift for the current day has been finished!!"), 500, "Gift Assign Failed");
    }

table 结构 ?

Schema::create('user_day', function (Blueprint $table) {
    $table->increments('id');
    $table->integer('user_id')->unsigned();
    $table->integer('day_id')->unsigned();
    $table->boolean('assigned')->default(0);
    $table->timestamps();
});

如何找到特定日期的用户数?

您需要在 eloquent 请求结束时使用计数选择器:

$userCount = users::all()->count();

也许你可以试试这个:

$dayId = $request->day_id;

// Get the count of users from the chosen day id
$userCount = User::where('day_id', '=', $dayId)->count();

// Set the limit and make a validation
$dayLimit = 5
   if ($userCount > $dayLimit) {
    dd('Limit exceeded');
   }
   else {
    dd('Within limit');
   }

编辑:按照建议,您可以创建一个 UserLog 模型和迁移,以便以后进行更轻松的查询。请参阅下面的示例代码:

$dayId = $request->day_id;

// Get today's date

   $timeStamp = Carbon::now()->format("h:i A");

// Check first if there's an existing log

  $findIfThereIsLog = UserLog::where('user_id', '=', Auth::User()->id)
  ->whereDate('created_at', Carbon::today()->startOfDay())
  ->first();

// Proceed with the logging if there's none

   if ($findIfThereIsLog === null) {

    $newUserLog = new UserLog;

    $newUserLog->user_id = Auth::User()->id;
    $newUserLog->day_id = $dayId;
    $newUserLog->save();

  }

  else {

    // Do nothing

  }

从那里您可以轻松地进行如下查询:

// Get the number of users from a particular day id

$dayId = $request->day_id;

$getUserFromDayId = UserLog::where('day_id', '=', $dayId)->count();

获取当天相关的用户数。

public function assign_prize(Request $request)
{
   
   $day = Day::withCount('users')->find($request->day_id);

   if ($day->users_count > $day->gift_limit) {
       return problem(__("Gift for the current day has been finished!!"), 500, "Gift Assign Failed");
   }