我有这段代码,只过滤那些有大约customerRewards个与某个客户有关的公司.whereHas()过滤器工作正常,但customerRewards from $的结果也包含了不同客户ID的项目.

$companies = Company::with(['customerRewards'])  // This is the problem
    ->has('customerRewards')
    ->whereHas('customerRewards', function(Builder $q) use ($customer) {
        $q->where('customer_id', $customer->id);  // This works as expected
    })
    ->get();

如何过滤$与Collection ?

推荐答案

在Laravel 9.x及以上版本中,您可以使用withWhereHas()来紧急加载customerRewards关系,为那些为特定客户提供奖励的公司.

$companies = Company::withWhereHas('customerRewards', function ($query) use ($customer) {
    $query->where('customer_id', $customer->id);
})->get();

Php相关问答推荐

在php中有没有办法比较两个包含相同枚举类型的枚举数组

LaravelEloquent 的地方条件父/子与第三模型多对多

将变体设置字段添加到WooCommerce中的特定变量产品

Sylius php -如何将购物车传递到小枝模板(Sylius模板事件)

使用MySQLi使用连接字符串设置字符集

函数存储到变量中

即使在WooCommerce购物车中添加了两次产品,也要将所有项目设置为空白行

如何判断php中wordpress路径之外的文件夹是否存在?

无法在 Laravel 中实例化抽象类 ProductAbstract

使用 wp_footer 挂钩添加一些 CSS 不起作用

在 WooCommerce 管理变量产品中启用其他变体图像

当所有对象都属于同一类型时,我可以省略 PHP in_array() 中的 strict 参数吗?

PHP - 计算非数值数组

在WooCommerce购物车和 checkout 页面中更改总计文本

Laravel 路由参数中的 ":" 是什么?

在 Symfony 测试中何时使用 TestCase 而不是 KernelTestCase

我需要获取传递到这个数组中的数据,但我没有得到它,因为在 Laravel 中数组是这样出现的

使用循环和引用而不是递归创建分层/父子数组

如何从 PHP 中的字符串位置排除图像扩展名

getenv() 有时在 CodeIgniter 4 中返回 false.为什么?