如何从关系数据中搜索?在 laravel

How to search from relationship data ? In laravel

public function scopeSearch($query, $value)
{
    $searchValues = explode(' ', $value);
    if (!$value) return $query;
    return $query->where(function ($q) use ($searchValues) {
        foreach ($searchValues as $token) {
            $q->orWhere('name', 'like', "%{$token}%");
            $q->orWhere('street', 'like', "%{$token}%");
        }
    });
}

我要搜索资料。该型号还有

public function brands()
{
    return $this->belongsToMany(Brand::class, 'dealer_brands');
}
public function province()
{
    return $this->belongsTo(Province::class);
}

如何从关系中获取数据。像 Dealer(model) 有数据 Nmae = josh,brand_id = 1 {brand.name = samsung},province_id = 2 (province.name = "aligora")。当我搜索 Josh Samsung Alogora 时,我想获取数据。当我只搜索aligora时,我想获取具有省份aligora的模型数据。如何修改代码?

查看您的模型关系。这可能对你有用

    public function scopeSearch($query, $value)
    {
        if (!$value) return $query;
        $searchValues = explode(' ', $value);
        return $query->where(function ($q) use ($searchValues) {
            foreach ($searchValues as $token) {
                $q->where('name', 'like', "%{$token}%")
                    ->orWhere('street', 'like', "%{$token}%")
                    ->orWhereHas('brands', function ($sub_q) use ($searchValues) {
                        $sub_q->where('name', 'like', "%{$token}%")
                            ->orWhere('street', 'like', "%{$token}%");
                    })
                    ->orWhereHas('province', function ($sub_q) use ($searchValues) {
                        $sub_q->where('name', 'like', "%{$token}%")
                            ->orWhere('street', 'like', "%{$token}%");
                    });
            }
        });
    }

我不知道相关表中的列名,所以重复名称和街道。您可以根据要求更改