sourcecode

라라벨 웅변가 관계 가져오기 카운트

codebag 2023. 8. 1. 20:31
반응형

라라벨 웅변가 관계 가져오기 카운트

Laravel 5.3을 사용합니다.

테이블이 두 개 있습니다.

Articles
---------
id
cat_id
title

그리고.

Category
---------
id
parent_id
title

모델에서 관계를 정의했습니다.

// Article model
public function category()
{
    return $this->belongsTo(Category::class);
}

// Category model
public function children() 
{
    return $this->hasMany(Category::class, 'parent_id', 'id');
}   

Enweller를 사용하여 항목 수가 포함된 범주 목록을 쉽게 만들 수 있는 방법이 있습니까?어려운 점은 다음과 같은 범주를 그룹화하고 싶다는 것입니다.id_parent = 0즉, 하위 항목의 아티클 수와 함께 상위 범주만 표시하려고 합니다.

저는 그런 것을 시도했습니다:

    $category = new \App\Models\Category();
    $categoryTable = $category->getTable();

    return $category->leftJoin('article', 'article.cat_id', '=', 'category.id')
        ->whereIn('article.cat_id', function($query)
            {
                $query->select('cat_id')
                    ->from('categories')
                    ->where('categories.parent_id', ???)
                    ->orWhere($this->tableName .'.cat_id', $id);
            })
        ->groupBy('cat_id');

하지만 난 길을 잃었어요...

사용할 수 있습니다.withCount()5.3 버전부터 사용할 수 있습니다.

웅변적인 방문에 대한 자세한 내용은 https://laravel.com/docs/5.3/eloquent-relationships 을 참조하십시오.

정의articles()당신과의 관계Category모형화:

public function articles() 
{
    return $this->hasMany(Article::class, 'cat_id');
}

그런 다음 다음과 같이 시도할 수 있습니다.

Category::where('parent_id', 0)->withCount('articles')->get();

사용할 수 있습니다.hasManyThrough()모든 어린이 기사를 가져온 다음 기사 수를 멋진 작은 게터에 추가할 수 있는 웅변적인 방법입니다.나는 게터를 에 추가했습니다.$appends모델의 배열을 사용하여 Tinker 출력에 설명할 수 있습니다.

class Category extends Model
{

    protected $appends = [
        'articleCount'
    ];

    public function articles()
    {
        return $this->hasMany(Article::class);
    }

    public function children()
    {
        return $this->hasMany(Category::class, 'parent_id');
    }

    public function childrenArticles()
    {
        return $this->hasManyThrough(Article::class, Category::class, 'parent_id');
    }

    public function getArticleCountAttribute()
    {
        return $this->articles()->count() + $this->childrenArticles()->count();
    }
}

다음은 Tinker 출력입니다.

Psy Shell v0.8.0 (PHP 7.0.6 — cli) by Justin Hileman
>>> $cat = App\Category::first();
=> App\Category {#677
     id: "1",
     name: "Cooking",
     parent_id: null,
     created_at: "2016-12-15 18:31:57",
     updated_at: "2016-12-15 18:31:57",
   }
>>> $cat->toArray();
=> [
     "id" => 1,
     "name" => "Cooking",
     "parent_id" => null,
     "created_at" => "2016-12-15 18:31:57",
     "updated_at" => "2016-12-15 18:31:57",
     "articleCount" => 79,
   ]
>>> 

카테고리 쿼리를 문서가 있는 자식이 있는 쿼리로 제한하려면 다음을 사용하여 수행할 수 있습니다.has()방법:

Category::has('children.articles')->get();

자세한 내용은 다음과 같습니다.has()방법:

https://laravel.com/docs/5.3/eloquent-relationships#querying-relationship-existence

그리고.hasManyThrough()방법:

https://laravel.com/docs/5.3/eloquent-relationships#has-many-through

이렇게 하면 됩니다.

$category
->where('categories.parent_id', 0)
->leftJoin('article', 'article.cat_id', '=', 'categories.id')
->select('categories.id', \DB::raw('COUNT(article.id)'))
->groupBy('categories.id')
->get();

위의 쿼리는 범주 ID와 범주에 속하는 모든 아티클의 개수를 가져옵니다.

질문과 의견을 다시 읽은 후, 제가 올바르게 이해한 경우 해당 범주에 속하는 모든 기사의 수(parent_id = 0) + 하위 범주에 속하는 기사의 수(parent_id = (일부 범주의 ID)를 확인하십시오.

저는 이것을 쉽게 테스트할 방법이 없습니다. 하지만 저는 이 방법들이 효과가 있을 것이라고 생각합니다.

$category
->where('categories.parent_id', 0)
->leftJoin('article', 'article.cat_id', '=', 'categories.id')
->leftJoin('categories as c2', 'c2.parent_id', '=', 'categories.id')
->leftJoin('article as a2', 'a2.cat_id', '=', 'c2.id')
->select('categories.id', \DB::raw('(COUNT(article.id)) + (COUNT(a2.id)) as count'))
->groupBy('categories.id')
->get();

그 표지판에는 카테고리에 카운트라는 이름의 열이 있고 새 기사가 추가될 때마다 업데이트하는 것이 더 낫다고 생각합니다.퍼포먼스를 위해서.

  public function NoOfStudent()
    {
        return $this->hasMany(UserAssignment::class,'assignment_id','id');
    }



$assignment = Assignment::select('id','batch_id','title','description','attachment','last_submission_date',DB::raw('(CASE WHEN type = 9 THEN "Quiz Type"  ELSE "Descriptive" END) AS assignment_type'),DB::raw('(CASE WHEN status = 1 THEN "Assigned"  ELSE "Not Assigned" END) AS status'))
                      ->with('assignmentBatch:id,batch_number')
                      ->where('assignments.instructor_id',auth('api')->user()->id)
                      ->orderBy('created_at','DESC');
        if(!$request->user_id){
            $assignment =$assignment->withCount('NoOfStudent');
        }

Carlos_E.의 답변과 관련하여.where를 사용하는 대신 whereHas를 사용하여 쿼리를 개선할 수 있습니다.포함:

$agents = Agents::whereHas('schedule')
)->with('schedules')->get();

누군가가 여전히 이 문제를 겪고 있다고 확신합니다. 에이전트 모델과 예약 모델이 있다고 가정하면 다음과 같은 방법으로 해결할 수 있습니다. 즉, 한 에이전트의 일정이 많을 수 있습니다.

class Schedule extends Model {
  public function agent() {
    return $this->belongsTo(Agent::class, 'agent_id');
  }
}

class Agent extends Model {
  public function user(){
    return $this->belongsTo(User::class);
  }

  public function schedules(){
    return $this->hasMany(Schedule::class);
  }
}

일부 에이전트는 일정이 반드시 할당되지 않을 수 있으므로, 전화를 걸기 전에 해당 일정을 필터링했습니다.with()다음과 같은 방법:

$agents = Agents::whereIn(
    'id', 
    Schedule::distinct()->pluck('agent_id')
)->with('schedules')->get();

이것이 도움이 되길 바랍니다!

언급URL : https://stackoverflow.com/questions/41165726/laravel-eloquent-get-relation-count

반응형