Laravel,多个模型之间的多对多关系

时间:2019-09-01 14:31:14

标签: laravel eloquent pivot many-to-many relation

我有多个具有多对多关系的模型

这是模特

  • 新闻栏
  • 类别
  • 子类别
  • 批准的新闻
  • 待处理新闻

每个新闻部分可以具有多个类别

每个类别可以具有多个子类别

每个子类别可以具有多个批准的新闻待处理新闻

我想拥有新闻,其中包含类别子类别待批准/批准新闻

之类的东西

类别以及子类别批准新闻

我尝试使用数据透视表,但无法获得结果

模型如下

新闻栏

class NewsSection extends Model
{
     public function categories()
    {
    return $this->belongsToMany(Category::class);
    }
}

类别

class Category extends Model
{
    public function subcats(){
       return $this->belongsToMany(SubCategory::class);
    }
    public function newssections(){
      return $this->belongsToMany(NewsSection::class);
    }
}

子类别

class SubCategory extends Model
{
    public function category(){
     return $this->belongsTo(Category::class);
    }

    public function approvednews(){
     return $this->belongsToMany(ApprovedNews::class);
    }

   public function pendingnews(){
     return $this->belongsToMany(PendingNews::class);
   }

}

批准的新闻

class ApprovedNews extends Model
{

    public function subcategories (){
     return $this->belongsToMany(SubCategory::class);
   }
}

待处理新闻

class PendingdNewsextends Model
{

    public function subcategories (){
     return $this->belongsToMany(SubCategory::class);
    }
}

更新 这是我到目前为止所做的

  

$ news = Category :: with('subcats.approvednews')-> where('id',1)-> get();

我获得了所有批准的新闻,包括子类别和类别

如果我这样做的话,我该如何修改它以获得每个类别的特定子猫和获批准的新闻

  

$ news = Category :: with('subcats.approvednews')-> where('subcats.id',1)-> get();

我收到类似id歧义的错误

是否可以从关系中选择项目,例如对于的每个子猫仅返回 2个子猫 3个批准的新闻 >所选类别

获取每个 subcat 类别

批准新闻待处理新闻的计数

预先感谢

3 个答案:

答案 0 :(得分:2)

错误“错误,例如id模棱两可”意味着您需要像where('id', 1)一样在where('table.id', 1)中指定表,以便MySQL知道您要在哪个表中的哪个id列。 / p>

您可以constrain the models returned by with这样:

Category::with(['subcats' => function(Builder $query) {
    $query->where('id', '=', 1);
}]);

您还可以count relations

$subcat = SubCategory::withCount(['approvednews']);
$subcat->approvednews_count;

不可能限制急切的加载关系per the docs

一种解决方法可能是从ApprovedNews开始:

ApprovedNews::whereHas(['subcategories' => function(Builder $query) {
    $query->where('id', '=', 1);
}])->limit(10);

答案 1 :(得分:0)

对于如何使它起作用,我有一些建议。在您的评论中,您说在执行以下操作时遇到问题:

$items=Category::with('subcategory')->where('id',1)->get();

'subcategory'来自哪里?根据模型的外观,类别和子类别之间的关系称为subcats。因此,您需要将其更改为:

$items=Category::with('subcats')->where('id',1)->get();

如果将其转储出去,您应该看到将获得ID为1的类别,并加载了子类别。一种测试关系正常的方法如下:

$category = Category::find(1);
$subCats = $category->subcats()->get();
dd($subCats);

在您的人际关系中,建议您不要尝试使用SubCategory::class来使模型完全连接。

一旦测试了彼此之间的关系,就可以开始从a-> b-> c等进行测试。

答案 2 :(得分:0)

可能正在使用“嵌套的渴望加载”和“范围”,您可以执行类似的操作

$pendings = NewSection::with('categories.subCategories')->pending()->get()
$approved = NewSection::with('categories.subCategories')->approved()->get()

未经测试,但您可以尝试,可能需要进行一些修改,才能达到目标。

如果您想返回一个收藏夹,您可能希望将其合并

$approved->merge($pendings);

但是,您应该避免使用它。