【问题标题】:Laravel many to many relastionship countLaravel 多对多关系计数
【发布时间】:2021-12-27 22:27:18
【问题描述】:

我有两张桌子。用户和天,具有多对多的关系。 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 {for a specific day} 或类似的用户计数。有什么方法可以从数据透视表中获取计数? 此功能无效。

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");
    }

表结构?

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();
});

如何找到当天用户的用户数??

【问题讨论】:

    标签: sql laravel eloquent many-to-many laravel-query-builder


    【解决方案1】:

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

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

    【讨论】:

    • 顺便说一句,您可能不想从数据库中提取所有记录 (all)[返回模型集合] 然后只计算它们...您可以让数据库返回通过在构建器本身上调用 count 来计数(调用 count 而不是 all
    【解决方案2】:

    也许你可以试试这个:

    $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();
    

    【讨论】:

    • day_id 在 user_day 表中,而不是 users 表中。我需要从数据透视表中计数?? @miguban
    • 如果是这种情况,我认为最好创建一个 UserLog 模型和迁移,其中 user_id 和 day_id 列都是外键。假设用户不能有相同 day_id 的多条记录,您只需创建一个验证以确保您的应用程序每天仅记录一次用户 day_id。我将编辑我的答案以向您展示一个示例。
    • 我已经这样做了。这里我只需要 day_id=2 中的用户数。我需要计算用户数量。我有 user_day 数据透视表。有什么办法吗??可能是我的错误,我没有正确写 qn。我已经更新了 qn
    • 我已经更新了我的答案。希望对您有所帮助。
    【解决方案3】:

    获取与当天相关的用户数。

    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");
       }
    

    【讨论】:

      猜你喜欢
      • 2023-03-12
      • 2016-11-03
      • 2016-11-19
      • 2020-06-25
      • 2018-06-15
      • 2018-01-22
      • 2016-02-26
      • 2016-01-04
      • 2018-07-04
      相关资源
      最近更新 更多