php - Get all products except that already had discount?
问题描述
I have these two tables:
products table:
name - price - quantity - etc
discounts table:
type('percentage','numeric') - value - cancel - expired_at
Polymorphic relations: discountables table:
discount_id - discountable_id - discountable_type
there is Many To Many (Polymorphic)
between them. So I need to get all products except that already had discount + the products that had discount but it's over with expired_at
Product model:
public function discounts()
{
return $this->morphToMany('App\Models\Discount', 'discountable');
}
Discount Model:
public function products()
{
return $this->morphedByMany('App\Models\Product', 'discountable')->withTimestamps();
}
My wrong shut!:
public function index()
{
$products = Product::with('discounts');
return view('cp.discounts.index', compact('products'));
}
解决方案
You can use doesntHave method,
The follow query will retrieve all products that don't have any discounts.
Product::doesntHave('discounts')->get();
And if you want to get the products except it's over with expired_at
+ don't have any discounts, you can use whereDoesntHave
to add condition in closure:
Product::whereDoesntHave('discounts', function($query) {
$query->where('expired_at', '>', \Carbon\Carbon::now()->format('Y-m-d H:i:s'));
})->get();
推荐阅读
- python - 使用级别值过滤熊猫 df
- c++ - 使用 C++ 将完整的以太网数据包发送到特定 ip
- javascript - 如何在固定导航栏下方制作可滚动的div
- c++ - 在 Windows 上将 filesystem::path 转换为 char*
- javascript - Aurelia start setRoot 给出错误 No applicationHost was specified
- html - bootstrap:为什么我的 col-sm-offset-3 不起作用
- javascript - Concat , Join 淘汰赛 observableArry
- python - 出现错误“TypeError:预期的字符串或类似字节的对象”
- python - 用同一个键合并两个字典
- android - 如何使用颤振在 Firebase 云 Firestore 中添加多个节点