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

标签 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个批准的新闻>所选类别

获取每个子目录类别已批准新闻待处理新闻计数

提前致谢

最佳答案

错误“error like id ambigitude”意味着您需要在 where('id', 1) 中指定表,例如 where('table.id', 1) 以便 MySQL 知道您指的是哪个表中的哪个 id 列。

您可以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);

关于Laravel,多个模型之间的多对多关系,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57746847/

相关文章:

laravel - 我们可以为数据创建迁移,而不仅仅是表结构吗

Laravel,SQL 变量

mysql - 我正在尝试为我的 laravel 网站获取最近的聊天记录。但查询返回错误的输出

php - 你可以在数据库 Laravel 4 中插入声明的变量吗

laravel - Auth::user()->name 在 laravel 的包 View 中不起作用?

javascript - 如何将 Laravel 变量传递到我的 AngularJS View 中?

mysql - 在 Controller 的存储方法中添加两个查询

mysql - sql 合并行成列(多对多的情况)

mysql - 将多行结果合并为一个

sql - 使用带有 SQL 的数据透视表将一些列转置为行