【问题标题】:laravel relationship problems with pivot table数据透视表的laravel关系问题
【发布时间】:2021-03-09 18:10:40
【问题描述】:

我试图用数据透视表中的关系来解决这个问题。我有 3 个表(产品、集合、集合产品)

产品表 ID 姓名 size_id

集合表 ID 名字

collection_product 表 id(我知道......我必须使用附加和分离)但稍后我会弄清楚如何解决它) collection_id product_id

模型

产品型号

public function collections()
{
    return $this->belongsToMany(Collection::class);
}

集合模型

public function products()
{
    return $this->belongsToMany(Product::class, 'collection_product');
}

ProductCollection 数据透视表

class ProductCollection extends Pivot
{
    protected $table = 'collection_product';

    public function collections()
    {
        return $this->hasMany(Collection::class, 'collection_id');

    }

    public function products()
    {
        return $this->hasMany(Product::class, 'product_id');
    }
}

在我的 CollectionController 中,我想搜索一个集合,对于集合中显示的所有产品,我只想在刀片视图中显示尺寸为“SMALL”(size_id)的产品,但我不知道如何在我的控制器,因为首先我需要修复关系,然后弄清楚如何声明一个条件来获取我的 products 表的 size_id。

【问题讨论】:

  • 旁注:ProductCollection 上的关系 collectionsproducts 将是 belongsTo 而不是 hasMany

标签: laravel relationship


【解决方案1】:

您可以为您想要的集合预先加载产品并限制它加载的内容:

$col = Collection::with('products', fn ($q) => $q->where('size_id', ...))
     ->findOrFail(...);

@foreach ($col->products as $product)
   ...
@endforeach

您还可以获取所有产品并在迭代它们之前对其进行过滤:

$col = Collection::findOrFail(...);

@foreach ($col->products->where('size_id', ...) as $product)
    ...
@endforeach

【讨论】:

  • 很好!!实际上它有效 $products = $collection->products->where('size_id', $sizeId->id);
猜你喜欢
  • 2019-02-19
  • 2017-07-22
  • 2014-09-29
  • 2014-08-26
  • 1970-01-01
  • 2018-12-16
  • 1970-01-01
  • 2015-09-21
  • 1970-01-01
相关资源
最近更新 更多