1

我有 Estate_object 表,其中包含有关房地产的信息,例如:地址、城市、地区等。然后我有一个单独的表,其中仅包含对象的特定属性,例如表中的一个是 objects_near。我为此制作了单独的表,因为这些模型中的每一个都可以保存多个值(它们是复选框),例如 objects_near 不能保存值,例如 - 停车、机场、查看、存储等。所以为了转义我制作的 Estate_object 表中不必要的列和空字段Estate_objects 表和保存属性的表之间的多态多对多关系。在我看来,我想做一个过滤器并从 Estate_object 表中查询东西工作正常。要过滤属于一个或多个房地产对象的属性,我有复选框。例如,要查询庄园附近的对象,我有带有多个选项的复选框。

这就是我的复选框的样子:

<div class="form-group align-items-center">
  <label class="col-form-label text-md-right">{{ trans('admin.estate-obj.label.columns.objects_near') }} 
  </label><br>
     @foreach($estate_objects_near as $objects_near)
         <input type="checkbox" id="{{ $objects_near->name }}" name="objects_near[]" value="{{ 
          $objects_near->id }}">  
       <label for="{{ $objects_near->name }}">{{ $objects_near->name }} </label>
     @endforeach  
/div>

Estate_object_near 模型:

  public function estateObj()
    {
        return $this->morphToMany(EstateObj::class, 'estateable');
    }

EstateObj 模型:

   public function objectsNear()
    {
        return $this->morphedByMany(Estate_objects_near::class, 'estateable');
    }

房地产对象控制器:

   function( $query) use ($request) {

                if($request->has('address')){
                    $query->where('address', $request->address);
                }

                if($request->has('price')){                      
                    $query->whereBetween('price', [$request->price['min'], $request->price['max']]);
                }

                if($request->has('room_qty') ){
                    $query->where('room_qty', $request->room_qty);
                }

                // trying to access properties which are selected in checkbox and related to estate 
                 object
               if($request->has('objects_near')){

                $objNear = Estate_objects_near::find(1);
                $obj = $objNear->estateObj;
                $query->where($obj, $request->objects_near);
            }

             
            });

如果我转储 $obj,我将获得与数据透视表 'estateable' 的关系,并且我可以看到哪个属性与特定的房地产 obj 相关,但是当我尝试执行时,它会显示 SQLSTATE[HY093]:无效参数号:混合命名和位置参数。我也尝试使用 whereHas 函数,但随后出现此错误 - 传递给 Illuminate\Database\Eloquent 的参数 1 必须是一个实例。

也尝试过 whereHasMorph :

$query->whereHasMorph('estateable', [Estate_objects_near::class], function ($query) {
     $query->where('id', $request->objects_near);
     })->get();
                

这导致“调用未定义的方法 App\Models\EstateObj::estateable()”

非常感谢您的建议。

4

1 回答 1

0

以下查询对我有用:

         if($request->has('objects_near')){
            $query->whereHas('objectsNear', function ($query) use ($request) {
            $query->whereIn('estate_objects_near.id', [$request->get('objects_near')]);
            })->get();
        }

事实证明 whereHasMorph 只适用于 morphTo 关系。如果有人有同样的问题并想了解更多我的代码结构,请告诉我。

于 2020-09-01T10:52:24.930 回答