简体   繁体   English

获取 pivot id (Laravel) 的所有数据

[英]Get all data where pivot id (Laravel)

Is there the best way/the simplest way to get all data where pivot?有没有最好的方法/最简单的方法来获取 pivot 的所有数据? I tried this $article = Article::with('category')->wherePivot('category_id', $category)->get();我试过这个$article = Article::with('category')->wherePivot('category_id', $category)->get(); but i got error但我有错误

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

The relation is many to many关系是多对多的

Article文章

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

Articles_Has_Categories文章_有_分类

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

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

Category类别

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

Please try this:请试试这个:

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

If you use $category as array the use $query->whereHas('category_id', $category);如果您使用$category作为数组,则使用$query->whereHas('category_id', $category); or else if you use $category is a single id $query->where('category_id', $category);否则,如果您使用$category是单个 id $query->where('category_id', $category);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM