简体   繁体   English

在创建资源集合之前过滤一个 model

[英]Filter a model before you create an resource Collection

I am looking for a way that my ProductResource Collection will only include products with active prices.我正在寻找一种方法,使我的ProductResource Collection 仅包含具有有效价格的产品。

In my routes/api.php am using a Collection as so:在我的routes/api.php中,我这样使用Collection

Route::get('/product', function (Request $request) {
  return new ProductCollection(
    Product::all()
  );
});

In the model App\Models\Product there is a relationship for prices在 model App\Models\Product中存在价格关系

public function prices () {
  return $this->hasMany(ProductsPrice::class);
}

and in the App\Models\ProductsPrice there is a scopeIsActive that I want to call before my collection is created.App\Models\ProductsPrice中有一个 scopeIsActive 我想在创建我的集合之前调用它。

public function scopeIsActive($query)
{
  return $query->where('is_active', true);
}

Is there a way I can call this isActive scope without creating a Controller just to query the Products with a active price and put that in a ResourceCollection in the routes/api.php , like so?有没有一种方法可以调用此isActive scope 而无需创建Controller来查询具有有效价格的产品并将其放入routes/api.phpResourceCollection中,就像这样?

Route::get('/product', function (Request $request) {
  return new ProductCollection(
    Product::all()->prices()->isActive()
  );
});

You can do like this.你可以这样做。

Route::get('/product', function (Request $request) {
  return new ProductCollection(
    Product::with(['prices' => function($query) {
        $query->isActive();
    }])->get()
  );
});

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

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