通过 pivot table id, laravel 获取所有结果

get all results by pivot table id, laravel

我有 laravel 多对多关系

我想在控制器中获取所有广告,类别 ID,示例 1

怎么了?如何通过 pivot table categories_id = 1?

获取所有模型
    $category_details = Categories::where('slug','=', $category_slug)->first();

    $advertisements = Advertisement::with(['categories'=> function($query){
        $query->wherePivot('categories_id', $category_details->id);
    }])->get();

您必须将 $category_details 变量传递给 Closure

$advertisements = Advertisement::with(['categories'=> function($query) use($category_details) {
        $query->wherePivot('categories_id', $category_details->id);
    }])->get();

我认为将您的 Categories 模型重命名为 单数形式并为其添加类似的关系:

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

那么你可以简单地这样做:

$category = Category::where('slug','=', $category_slug)->firstOrFail();

return $category->advertisements()
    ->with('categories')
    ->get();

或者你可以让它更漂亮一点:

return Category::where('slug','=', $category_slug)
    ->firstOr(fn() => Category::make())
    ->advertisements()
    ->with('categories')
    ->get();