简体   繁体   English

在 Laravel 中的 JOIN 中使用 scope Eloquent

[英]Use a scope in a JOIN in Laravel Eloquent

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 .我正在尝试获取所有具有有效价格的产品,并在ProductPrices Model中使用 scope 显示它们和有效价格。 My Products Model has an hasMany relation with prices:我的产品 Model与价格有很多关系:

Product.php (Model)产品.php (型号)

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:我的价格 Model有一个 scope 是活动的,它检查价格在这个日期是否有效:

ProductsPrices.php (Model) ProductsPrices.php (型号)

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.属性 [prices] 在 Eloquent 构建器实例中不存在。

or test2或测试2

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.方法 Illuminate\Database\Eloquent\Collection::prices 不存在。

Why can't I access the ->prices() on my Product Model ?为什么我无法访问我的产品 Model上的 ->prices() ? Should I not use eloquent for this and go for the Query Builder of Laravel?我不应该为此使用 eloquent 和 go 作为 Laravel 的查询生成器吗?

I think a combination of with and whereHas might work:我认为结合使用withwhereHas可能会起作用:

$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();

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

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