php Laravel的雄辩获取关系计数

6tr1vspr  于 2023-11-16  发布在  PHP
关注(0)|答案(7)|浏览(101)

我使用Laravel 5.3。
我有两张table:

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


有没有一个简单的方法使用口才有一个列表与文章计数的类别。困难的是,我想组类别在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');


但我迷失了...

9njqaruj

9njqaruj1#

您可以使用withCount()。它从5.3版本开始可用
欲了解更多有关雄辩的信息,请访问:https://laravel.com/docs/5.3/eloquent-relationships

zkure5ic

zkure5ic2#

Category模型中定义一个articles()关系:

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

字符串
然后你可以尝试它:

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

eh57zj3b

eh57zj3b3#

你可以使用hasManyThrough() Eloquent方法来获取所有children的Articles,然后将article计数添加到一个漂亮的小getter中。我将getter添加到模型上的$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,
   ]
>>>


如果你想限制你的Category查询到那些有文章的子条目,你可以使用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

ncecgwcz

ncecgwcz4#

关于Carlos_E.的回答:
您可以通过使用whereHas而不是whereIn来改进查询:

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

字符串

du7egjpx

du7egjpx5#

这应该是可行的:

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


这就是说,我认为你最好有一个名为count in categories的列,并在每次添加新文章时更新它。

f2uvfpb9

f2uvfpb96#

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

字符串

szqfcxe2

szqfcxe27#

我相信有人仍然在经历这个问题,我能够用下面的方法解决它,假设我有一个Agent模型和一个Schedule模型,即一个Agent可能有许多时间表:

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


希望这有帮助!

相关问题