简体   繁体   中英

Get all data where pivot id (Laravel)

Is there the best way/the simplest way to get all data where pivot? I tried this $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
  • content
public function category(){
        return $this->belongsToMany(Category::class, 'articles_has_categories', 'article_id', 'category_id');
    }

Articles_Has_Categories

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

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

Category

  • 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); or else if you use $category is a single id $query->where('category_id', $category);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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