首页 > 解决方案 > 获取枢轴id(Laravel)的所有数据

问题描述

有没有最好的方法/最简单的方法来获取所有数据的枢轴?我试过了,$article = Article::with('category')->wherePivot('category_id', $category)->get();但我得到了错误

SQLSTATE[42S22]: Column not found: 1054 Unknown column 'pivot' in 'where clause' (SQL: select * from `articles` where `pivot` = category_id)

关系是多对多的

文章

  • ID
  • 内容
public function category(){
        return $this->belongsToMany(Category::class, 'articles_has_categories', 'article_id', 'category_id');
    }

文章_有_分类

  • ID
  • article_id
  • 类别ID
public function article ()
    {
        return $this->belongsTo(Article::class,'article_id');
    }

    public function category ()
    {
        return $this->belongsTo(Category::class,'category_id');
    }

类别

  • ID
  • 姓名
public function article(){
        return $this->belongsToMany(Article::class, 'articles_has_categories', 'category_id', 'article_id');
    }

标签: phplaraveleloquentlaravel-7

解决方案


请试试这个:

    $article = Article::with(['category' => function($query) use ($category) {
            $query->where('category_id', $category);
        }
    ])->get();

推荐阅读