【发布时间】:2020-03-17 00:47:55
【问题描述】:
我有两个模型
1 - 父子类别
class Category extends Model
{
protected $primaryKey = 'id';
public $fillable = ['slug','title','icon','parent_id'];
/**
* Get the index name for the model.
*
* @return string
*/
public function childs() {
return $this->hasMany('App\Category','parent_id','id') ;
}
public function parent()
{
return $this->belongsTo('App\Category', 'parent_id','id');
}
public function posts(){
return $this->belongsToMany('App\Post', 'category_post');
}
public function latestposts(){
return $this->belongsToMany('App\Post', 'category_post')->latest()->limit(3);
}
}
2 - 使用 belongsToMany->Category 发布模型
class Post extends Model
{
protected $primaryKey = 'id';
public $fillable = ['user_id','slug','title','excerpt','content','keyword','img','status'];
protected $table = 'posts';
public function cat_posts(){
return $this->belongsToMany('App\Category', 'category_post');
}
}
示例数据树视图:
1-category parent
|- 1-child category -> with 5 post
|- 2-child category -> with 3 post
现在,在查看主要部分 ->(父类别)时,我想显示所有子类别中的所有帖子 得到帖子数=8的结果
通过分页 我该怎么做呢
【问题讨论】:
标签: php mysql laravel laravel-5 eloquent