laravel 根据属性筛选结果

laravel filter the results based upon attributes

我有一个名为 "motors" 的主表格,我将它们的属性保存在子 table "motor_attributes" 中。属性是动态的,它们可以包含任何 id 和值。 关系是一对多的关系。 问题是我无法搜索任何属性。它给了我相同的父 table 项 "enteries"。

我想说得更清楚一点。每次它都给我 6 个条目。即使我更改了 $request->get('body_condition') 的值。手动。因为它的查询字符串。 我想根据这些属性最好地过滤电机。 任何帮助将不胜感激。 它只是隐藏属性而不是主要广告。 任何帮助将不胜感激。 提前致谢

```````````

        $perPage = 20;
        $motorQuery = Motor::with(['advertisementPhotos', 'country', 'city', 'customer.dealer','favouriteAd', 'adAttributes' => function ($query) use ($request){

             // dd($request->get('body_condition'));
             $query->where('integer_value',$request->get('body_condition'));
             $query->with('attribute');
             $query->with('adAttributeValue');
             $query->where('show_listing_page',1);
        //;
        //  return $query->take(2);

          }])
        ->where('status', 1)
        ->where('date_expiry', '>=', date('Y-m-d') . ' 00:00:00');


    if (request()->filled('city')) {
        $motorQuery->where('city', request()->get('city'));
    }
    if (request()->filled('keywords')) {
        $motorQuery->where('title', 'like', '%' . request()->get('keywords') . '%');
    }
    if (request()->filled('from_price')) {
        $motorQuery->where('price', '>=', request()->get('from_price') );
    }
    if (request()->filled('to_price')) {
        $motorQuery->where('price', '<=', request()->get('to_price') );
    }


    if (request()->hasCookie('country')) {
        $motorQuery->where('country', request()->cookie('country')->first()->id);
    }

    $data['allMotors'] =  $allMotors = $motorQuery->orderBy('featured', 'desc')->orderBy('date_posted', 'desc')->paginate($perPage);

```

您必须尝试使用​​ join 进行属性筛选。此外,如果任何 table 与属性相关,并且您希望从那些 table 中获取一些数据,也可以加入这些 table。尝试这样的事情:

$motorQuery = Motor::with(['advertisementPhotos', 'country', 'city', 'customer.dealer','favouriteAd'])
            ->join('ad_attribute_value', 'ad_attribute_value.motor_id', '=', 'motor.id')
            ->where(function($query) use ($request){
                       if($request->get('body_condition') != '')
                           $query->where('integer_value', '=', $request->get('body_condition'))
            })
            ->where('status', 1)
            ->where('date_expiry', '>=', date('Y-m-d') . ' 00:00:00');

看看它是否适合你。

好的,正如我从您的代码中看到的那样,您试图在此处过滤电机并在错误的地方使用过滤器。

with 子句中的过滤器只会过滤要预先加载的关系,而不是父模型。

要在 Eloquent 语法中过滤父模型,请使用 "has" 或快捷方式 "whereHas":

$perPage = 20;
$bodyCondition = request('body_condition');
$motorQuery = Motor::with(['advertisementPhotos', 'country', 'city', 'customer.dealer','favouriteAd', 'adAttributes.attribute', 'adAttributes.adAttributeValue'])
    ->whereHas('adAttributes', function ($q) use ($bodyCondition) {
        $q->where('integer_value', $bodyCondition)
          ->where('show_listing_page',1);
    })
    ->where('status', 1)
    ->where('date_expiry', '>=', date('Y-m-d') . ' 00:00:00');