首页 > 解决方案 > Laravel WhereHa 拥有所有数据控制权

问题描述

我有一张客户表。这些客户有一个 custumer_request 表,一个客户可以有多个索赔记录。还有一张地板表。倍数表有一个与客户索赔表关联的 customer_request_floors 表。它们都是相互关联的。我想在过滤客户的时候根据选择的倍数过滤有需求的客户。

在下面我使用的搜索中,我想根据客户的最新要求对其进行过滤。当我按如下过滤时,它会为我带来该用户其他请求的链接记录。例如,让客户有 2 个请求。让它们成为两个不同的楼层记录。我想在最后一个请求的倍数之间进行搜索。当我按如下过滤时,它会在 2 个请求中为我带来注册的 floor_id。我正在使用模型拍摄您的最后一个请求。能帮忙过滤吗?

我真正想要寻找的是过滤我在数据透视表中发送的带有 floor_id 的记录,这取决于客户的最终需求。

客户型号:

    public function lastRequest()
    {
        return $this->hasOne(CustomerRequest::class)->latest();
    }

搜索型号:

    $this->customers = $this->customers->whereHas('lastRequest', function ($customer_request){
        $customer_request->whereHas('floors', function($floors) {
           $floors->whereIn('floor_id', $this->params['floor_ids']);
        });
    });

客户请求模型

    public function floors()
    {
        return $this->belongsToMany(Floor::class, 'customer_request_floors');
    }

customer_request_floors 数据透视表

    protected $fillable = [
       'customer_request_id', 'floor_id'
    ];

标签: phpmysqllaraveleloquentrelationship

解决方案


推荐阅读