Laravel 交叉检查查询

Laravel cross check query

我想像这样显示我的品牌页面:url/discount/{brand-slug} 到目前为止我可以通过这样的方式来完成它:

$brandspromotion = Brand::where('slug', $slug)->OfStatus('Active')->firstOrFail();

当我尝试仅获取具有相同 brand_id 且其 id 保存在名为 discounts.

的第 3 个 table 中的产品时出现问题

In the simple words: I want to get only discounted products of each brand.

逻辑

  1. 折扣 table 节省 product_id
  2. 产品 table 节省 brand_id
  3. 品牌必须从 productsdiscounts table.
  4. 找到自己的 id

代码

到目前为止我有这段代码,但它不起作用:)

public function brandspromotions($slug) {
    $promotions = Discount::Valid()->get();
    $grouped = $promotions->map(function ($item, $key) {
      return $item->products->brand_id;
    });
    $brandspromotion = Brand::where('slug', $slug)->OfStatus('Active')
      ->where('id', $grouped)->get();
    return view('front.brandspromotions', compact('brands', 'brandspromotion'));
  }

更新

product model

public function discount(){
    return $this->belongsTo(Discount::class, 'product_id', 'id');
  }
public function brand(){
     return $this->belongsTo(Brand::class);
  }

brand model

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

discount model

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

如果您有品牌代言人,并且只想购买在 discounts table 中有记录的该品牌的产品:

Product::has('discount')
    ->whereHas('brand', function($q) use($slug) {
        $q->where('slug', $slug);
    })
    ->get();

其中 discountbrandProduct 模型中定义的关系。