Php 用雄辩的语言帮助质疑关系

Php 用雄辩的语言帮助质疑关系,php,laravel,eloquent,Php,Laravel,Eloquent,我的代码库中有这个查询 $listings = Tag::has('listings')->with(['listings' => function ($query) use ($request) { $query->where('moderated', 1) ->where('active', 1); if($request->query('free') == true) {

我的代码库中有这个查询

$listings = Tag::has('listings')->with(['listings' => function ($query) use ($request) {
            $query->where('moderated', 1)
                ->where('active', 1);

            if($request->query('free') == true) {
                $query->where('cost', '0.00');
            }

            if($request->query('type') != "") {
                $query->with(['types' => function($q) use ($request) {
                    $q->whereIn('id', explode(",", $request->query('type')));
                }]);
            }

            $query->with('primaryImage');
        }])
            ->paginate(3);
我试图做的是根据GET请求中的内容添加部分查询(此位起作用),不起作用的是对关系的查询

在这里,我查询的标签可以有许多列表,每个列表可以有许多类型,我只想返回列表与过滤器参数匹配的标签,即只显示成本为“0.00”的列表,然后只显示列表与get请求中的类型匹配的标签

因此,如果用户在GET请求中发送
type=1,2,3
,我想返回具有列表的标记,其中类型关系包含1个ID,这可能吗

列表上的类型关系如下所示

public function types() {
    return $this->belongsToMany('App\Type');
}
public function listings() {
    return $this->belongsToMany('App\Listing');
}
从类型到列表的关系如下所示

public function types() {
    return $this->belongsToMany('App\Type');
}
public function listings() {
    return $this->belongsToMany('App\Listing');
}
正如您所说,“每个列表可以有多种类型”

在您的列表::类中更改此选项

public function types() {
    return $this->hasMany('App\Type');
}

不要用has和with,也许你可以用whereHas

$listings = Tag::whereHas('listings', function($query){
            $query->where('moderated', 1)
                ->where('active', 1);

            if($request->query('free') == true) {
                $query->where('cost', '0.00');
            }

            if($request->query('type') != "") {
                $query->whereHas('types', function($q) use($request){
                    $q->whereIn('id', explode(",", $request->query('type')));
                });
            }

            $query->with('primaryImage');
        });

我已经试过了,现在没有返回带有列表属性的标记了吗?当我知道其中两个标记至少各有一个列表时。如果希望返回查询包含列表关系,则需要使用with或直接在blade文件中惰性加载加载关系,WHERHAS仅用于在相关模型内进行查询。