Laravel Scope запрашивает подсчет типа проекта для каждого пользователя - PullRequest
0 голосов
/ 06 февраля 2019

Я хотел бы знать, как я могу использовать Scopes на модели Laravel для подсчета каждого типа проекта для каждого пользователя, которого я имею.

У каждого проекта есть фаза типа "выиграть, проиграть, оценить" и иметьотношения с пользователем.

Я хочу знать, сколько проектов у каждого пользователя по типу:

Пользователь1: выиграть 2, оценка 5 проиграна, 0

Пользователь2: выиграть2 цены 1 потеря 3

Таблица: Таблица проектов

Модель проекта:

protected $table = 'projects';
protected $fillable = ['name', 'phase', 'estimated_date', 'user_id','client_id', 'comments', 'docs', 'approved_docs','contact_id'];

public function user()
{
    return $this->hasOne(User::class, 'id', 'user_id')->withTrashed();
}

**

Ответы [ 2 ]

0 голосов
/ 06 февраля 2019

Для лучшего понимания проблемы покажите свою схему таблицы базы данных для проекта

С небольшой предоставленной вами информацией, что-то подобное может работать ...

Модель проекта:

<?php

namespace App;

use App\User;

/**
 * Assumption: You have a table field called **phase** on the project model.
 */
class Project extends Model
{
    /**
     * The relationship: A project belongs to a user.
     */
    public function user()
    {
        return $this->belongsTo(User::class);
    }

    /**
     * Query for WINs.
     */
    public function scopeWin($query)
    {
        return $query->where('phase', 'win);
    }

    /**
     * Query for PRICINGs.
     */
    public function scopePricing($query)
    {
        return $query->where('phase', 'pricing);
    }

    /**
     * Query for LOSSes.
     */
    public function scopeLost($query)
    {
        return $query->where('phase', 'lost);
    }

    /**
     * Query for total number of projects.
     */
    public function totalCounts()
    {
        $wins_count     = $this->win->count();     // call to scopeWin($query)
        $pricings_count = $this->pricing->count(); // call to scopePricing($query)
        $losses_count   = $this->lost->count();    // call to scopeLost($query)

        $total_project_counts = $wins_count + $pricings_count + $losses_count;

        return $total_project_counts;
    }
}

Модель пользователя:

<?php

namespace App;

use App\Project;
use Illuminate\Foundation\Auth\User as Authenticatable;

class User extends Authenticatable
{
    /**
     * The relationship: A user has many projects.
     */
    public function projects()
    {
        return $this->hasMany(Project::class);
    }

    /**
     * Total projects for this user.
     *
     * Using existing relationship instance, 
     * make a call to the appropriate method on the project model.
     */
    public function totalProjectCounts()
    { 
        return $this->projects()->totalCounts();
    }

    // User projects with phase Win.
    public function projectWinCounts()
    { 
        return $this->projects()->win()->count();
    }

    // User projects with phase Pricing.
    public function projectPricingCounts()
    { 
        return $this->projects()->pricing()->count();
    }

    // User projects with phase Lost.
    public function projectLostCounts()
    { 
        return $this->projects()->lost()->count();
    }
}

Для данного пользователя вы можете проверить отдельные итоги следующим образом:

$user->totalProjectCounts(); 

auth()->user()->totalProjectCounts(); 

Auth::user()->totalProjectCounts(); 

Надеюсь, это поможет.В противном случае предоставьте больше информации о проблеме, с которой вы столкнулись.

<table>
    <tr>
        <th> USER </th>
        <th> WIN </th>
        <th> PRICING </th>
        <th> LOST </th>
        <th> TOTAL </th>
    </tr>

    @foreach ($users as $user)
    <tr>
        <td>{{ $user->name }}</td>
        <td>{{ $user->projectWinCounts() }}</td>
        <td>{{ $user->projectPricingCounts() }}</td>
        <td>{{ $user->projectLostCounts() }}</td>
        <td>{{ $user->totalProjectCounts() }}</td>
    </tr>
    @endforeach
</table>

Я думаю, что assignTo (User :: class) более подходит вместо hasOne (user :: class)) .

0 голосов
/ 06 февраля 2019

Как насчет:

<?php 
User::with(['projects' => function($q){
                return $q->groupBy('projects.phase')
            ->select(\DB::raw("count(*) as count"), 'user_id');

            }])->get();

Если вы хотите область действия, затем в user.php создайте:

<?php 

public function scopePhasecounts($query){
                return $query->with(['projects' => function($q){

                    return $q->groupBy('projects.phase')
                    ->select(\DB::raw("count(*) as count"), 'user_id');
                }])
            }

, а затем вы можете сделать

User::phasecounts()->get()
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...