我使用Laravel 5.3.
我有2张桌子:
Articles
---------
id
cat_id
title
Run Code Online (Sandbox Code Playgroud)
和
Category
---------
id
parent_id
title
Run Code Online (Sandbox Code Playgroud)
我在模特中定义了我的关系:
// Article model
public function category()
{
return $this->belongsTo(Category::class);
}
// Category model
public function children()
{
return $this->hasMany(Category::class, 'parent_id', 'id');
}
Run Code Online (Sandbox Code Playgroud)
有没有一种简单的方法可以使用Eloquent来列出包含文章数量的类别.困难在于我想将类别分组在哪里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');
Run Code Online (Sandbox Code Playgroud)
但我迷路了......
kap*_*dev 35
你可以使用withCount().它有5.3版本
有关雄辩访问的更多信息:https://laravel.com/docs/5.3/eloquent-relationships
您可以使用hasManyThrough()Eloquent方法获取所有儿童文章,然后将文章计数添加到一个漂亮的小吸气器中。我将吸气剂添加到$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();
}
}
Run Code Online (Sandbox Code Playgroud)
这是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,
]
>>>
Run Code Online (Sandbox Code Playgroud)
如果要将类别查询限制为那些子项中包含文章的查询,则可以使用以下has()方法:
Category::has('children.articles')->get();
Run Code Online (Sandbox Code Playgroud)
以下是有关has()方法的更多信息:
https://laravel.com/docs/5.3/eloquent-relationships#querying-relationship-existence
和hasManyThrough()方法:
https://laravel.com/docs/5.3/eloquent-relationships#has-many-through
Define a articles() relation in your Category model as:
public function articles()
{
return $this->hasMany(Article::class, 'cat_id');
}
Run Code Online (Sandbox Code Playgroud)
Then you can try it as:
Category::where('parent_id', 0)->withCount('articles')->get();
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
44017 次 |
| 最近记录: |