Laravel 获取数据库中某个字段被设置为特定值的关系计数

Laravel get relation count where a field in the database is set to a certain value

我有一个任务模型和一个步骤模型。每个任务可以有多个步骤。我希望能够显示所有任务,包括进度条。进度条的长度会根据总步数和完成的总步数来计算。所以我会做这样的计算:

100% / $total_steps * $total_steps_completed

已完成的步骤在数据库中的状态设置为 1。我知道如何获取 $total_steps。我只是做了一个计数($task->steps)所以它计算了数组中的总行数。

但是我如何计算状态为 1 的步数?

任务模型:

class Task
{
    public function steps()
    {
        return $this->hasMany('App\Step');
    }
}

步模型:

class Step
{
    public function task()
    {
        return $this->belongsTo('App\Task');
    }
}

任务控制器:

class TasksController
{
    public function index()
    {
        $tasks = User::find(Auth::user()->id)->tasks->with('steps')->get();

        return view('tasks', compact('tasks');
    }
}

每个任务都属于一个用户,因此 User::find()->tasks 等等。

在我的 steps table 中,我有以下字段:

$table->integer('status');

这可以设置为 0 或 1。在我的任务 -> index.blade.php 视图中,我有一个简单的 foreach:

@foreach($tasks as $task)
    {!! $task->id !!} // This is 1 for example

    Total Steps: {!! count($task->steps) !!} // Returns 5 if there are 5 rows in the steps database with task_id `1` for example

@endforeach

现在,我需要计算状态设置为 1 的总步数,以便我可以执行计算并显示进度条。我想我应该在我的步骤模型中为此添加一个函数,或者一个范围。但我坚持这一点,所以任何指针将不胜感激。

您可以使用 "scope" laravel 功能。 你可以在这里找到一些关于它的信息

http://www.easylaravelbook.com/blog/2015/06/23/using-scopes-with-laravel-5/

您的 Step 模型基本上会采用此方法:

class Step extends Model
{
    public function scopeDone($query)
    {
        return $query->where('status', 1);
    }
}

那么您应该能够完成以下步骤:

Total Steps: {{ $task->steps()->done()->count() }}

注意:为了使用范围,重要的是将步骤作为关系(通过添加双括号)。否则你会得到一个没有范围功能的简单集合。

您可以将条件关系添加到 return 任务的所有已完成步骤:

任务

public function completedSteps()
{
    return $this->hasMany('App\Step')->where('status','=', 1);;
}

然后您可以获得您的任务以及步骤和已完成的步骤:

任务控制器

$tasks = User::find(Auth::user()->id)->tasks->with('steps', 'completed_steps')->get();

并且在您看来您可以访问 steps 并同时计算 completed_steps :

查看

count( $task->completedSteps()->get() );