laravel - 如何在范围内获得 Eloquent 关系
问题描述
$this 是命名空间App\Models\Product
;
protected $fillable = [ 'name', 'slug', 'company_id', 'original_price', 'discount_price', 'code', 'barcode', 'quantity', 'parent_id', 'position', 'status', 'short_description', 'long_description', 'approved', 'auto_approve' ];
代码:
public function childProducts()
{
return $this->hasMany(Product::class, 'parent_id', 'id');
}
我的范围
public function scopeActive($query) {
return $query->where('status', 1);
}
解决方案
你可以这样做:
public function scopeActive($query)
{
return $query->whereHas('childProducts', function($query) {
$query->where('status', 1);
});
}
更新: 检查数量
public function scopeActive($query)
{
return $query->where('quantity', '>', 0)->whereHas('childProducts', function($query) {
$query->where('status', 1)->where('quantity', '>', 0);
});
}
推荐阅读
- javascript - 为什么我得到参考错误,我的代码有什么问题?
- python - {foo:>7f} 在 Python f 字符串中做了什么?
- css - 如何使 CSS 绘图始终在每个屏幕中固定显示?
- flutter - 无法为模拟器构建应用程序。在 iPhone 12 Pro Max 上启动应用程序时出错
- c# - 如何将控制器添加到 blazor wasm 以生成我的数据库的统计信息?
- google-workspace - 查看 Google Workspace Sites for Business 所需的自定义身份验证
- python-3.x - 我编写了一个简单的程序来自动化斐波那契数列,但它不起作用,我不知道为什么
- ios - CloudKit 记录 ID 不是唯一的
- javascript - Webpack - 如何使用异步功能导入脚本
- azure-pipelines - Devops 中的 AdvancedInstaller - 无法同步文件