Home > Net >  Use a scope in a JOIN in Laravel Eloquent
Use a scope in a JOIN in Laravel Eloquent

Time:02-01

I am trying to get all the products with active prices and display them and the active price using a scope in the ProductPrices Model. My Products Model has an hasMany relation with prices:

Product.php (Model)

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

My Prices Model has an scope is active that checks if the prices is active on this date:

ProductsPrices.php (Model)

public function scopeIsActive($query)
  {
    return $query->whereRaw(' timestampdiff(second, start_time, NOW()) >= 0')
                 ->where(function ($query) {
                    $query->whereRaw(' timestampdiff(second, end_time, NOW()) <= 0')
                       ->orWhereNull('end_time');
                  });
} 

I tried many different ways to get products with an active price and display them both. Things I feel should work, but don't, are:

Route::get('/test', function (Request $request) {
  return Product::join('products_prices', 'products.id', 'products_prices.product_id')
      ->prices->isActive()
      ->where('products.is_active', true)
      ->get();
});

I get the error:

Property [prices] does not exist on the Eloquent builder instance.

or test2

Route::get('/test2', function (Request $request) {
  $prices = DB::table('products_prices')->select('id');
  $product = Product::whereIn('id', $prices)->get();

  return $product->prices()->isActive()->get();
});

I get the error:

Method Illuminate\Database\Eloquent\Collection::prices does not exist.

Why can't I access the ->prices() on my Product Model? Should I not use eloquent for this and go for the Query Builder of Laravel?

CodePudding user response:

I think a combination of with and whereHas might work:

$products = Product::with(['prices' => function($query) {
    $query->isActive(); // to fetch prices relation that is active
}])->whereHas('prices', function($query) {
    $query->isActive(); // this one is to filter the products that has active price
})->get();
  • Related