【问题标题】:laravel BelongsToMany paginationlaravel BelongsToMany 分页
【发布时间】: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


    【解决方案1】:

    首先,您需要进行查询以从您的主要category 中获取所有subcategory

    在这个例子中,我假设第一个类别是一个主类别

    $subsCat = Category::first()->childs->pluck('id');
    

    之后,您可以获取所有这些类别的产品id

    Post::whereIn('category_post', $subsCat)->paginate(8);
    

    如果你不需要分页,你可以在一行中 使用来自 laravel collectioneach 就像这个

    $cat->childs->each(function($child){ 
       $child->posts;
    })
    

    您可以从文档中了解更多关于 eachwhereIn 的信息

    paginate 的第一个示例效率更高,因为它只会进行两次查询

    【讨论】:

      猜你喜欢
      • 2015-06-26
      • 2015-02-22
      • 2018-08-10
      • 2022-12-05
      • 2018-03-08
      • 2021-03-22
      • 2019-05-12
      • 2021-10-17
      相关资源
      最近更新 更多