首页 > 解决方案 > laravel 第二个连接返回查询为空

问题描述

我有这个查询

$products = DB::table('product_attributes')
        ->where('product_attributes.attribute_id', '=', $attri->id)
        ->joinoin('products', 'products.id', '=',
        ->get();

它返回

Collection {#2788 ▼
  #items: array:2 [▼
    0 => {#2785 ▶}
    1 => {#2786 ▶}
  ]
}

但后来我无法访问我的产品封面图片,所以我将查询更改为:

$products = DB::table('product_attributes')
        ->where('product_attributes.attribute_id', '=', $attri->id)
        ->join('products', 'products.id', '=', 'product_attributes.product_id')
        ->join('covers', 'covers.imageable_id', '=', 'products.id')
        ->get();

它返回:

Collection {#2805 ▼
  #items: []
}

空的!

我再次将查询更改为:

$products = DB::table('product_attributes')
        ->where('product_attributes.attribute_id', '=', $attri->id)
        ->leftJoin('products', 'products.id', '=', 'product_attributes.product_id')
        ->leftJoin('covers', 'covers.imageable_id', '=', 'products.id')
        ->get();

它返回:

Collection {#2807 ▼
  #items: array:2 [▼
    0 => {#2804 ▶}
    1 => {#2805 ▶}
  ]
}

但无法访问我的封面(与我的第一个查询相同)。

问题

我怎样才能访问我的产品与所有其他模型关系?

更多的...

这是与我的产品模型的其他一些关系

public function covers()
    {
        return $this->hasMany(Cover::class, 'imageable_id');
    }

    public function photos()
    {
        return $this->hasMany(Photo::class, 'imageable_id');
    }

    public function options(){
        return $this->belongsToMany(Option::class, 'product_options', 'product_id', 'option_id');
    }

    public function attributes(){
        return $this->belongsToMany(Attribute::class, 'product_attributes', 'product_id', 'attribute_id');
    }

    public function categories(){
        return $this->belongsToMany(Category::class, 'product_categories', 'product_id', 'category_id');
    }

标签: phplaravelquery-builder

解决方案


如果您设置了关系,则可以通过以下方式进行:

$products = Product::with(['covers','attributes'])->whereHas('attributes', function ($query) use ($attri) {
      $query->where('product_attributes.attribute_id', $attri->id);
})->get();

通过这种方式,您可以获得具有给定标识符的属性的所有产品,并且与这些产品一起,您还将检索封面和属性。

例如,要访问第一个产品中的封面或属性,您可以这样做$products->first()->covers


推荐阅读