簡體   English   中英

在 Laravel 中的 JOIN 中使用 scope Eloquent

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

我正在嘗試獲取所有具有有效價格的產品,並在ProductPrices Model中使用 scope 顯示它們和有效價格。 我的產品 Model與價格有很多關系:

產品.php (型號)

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

我的價格 Model有一個 scope 是活動的,它檢查價格在這個日期是否有效:

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');
                  });
} 

我嘗試了很多不同的方法來獲得有效價格的產品並同時展示它們。 我覺得應該起作用但不起作用的事情是:

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

我收到錯誤:

屬性 [prices] 在 Eloquent 構建器實例中不存在。

或測試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();
});

我收到錯誤:

方法 Illuminate\Database\Eloquent\Collection::prices 不存在。

為什么我無法訪問我的產品 Model上的 ->prices() ? 我不應該為此使用 eloquent 和 go 作為 Laravel 的查詢生成器嗎?

我認為結合使用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