繁体   English   中英

如何比较列值与其关系列值 laravel

[英]How to compare columns value to it's relationship column values laravel

我想根据它的关系表中的值过滤结果基本上我有两个表,即 product_supplier 和 product_competitor 以及 product_competitor 表中的 product_id 列

Product::with(['ProductCompetiter'])->where('sku' , 'A898-38')->first();

通过运行上面的查询,我得到以下结果以及 product_competitor

{
  "id": 1,
  "sku": "A898-38",
  "brand_id": 1,
  "supplier_id": 2,
  "name": "Sabots noirs microfibre Abeba pointure 38",
  "stock": 3,
  "price": "49.45",
  "real_price": 5,
  "last_stock_update": "2021-12-10",
  "last_price_update": "2021-12-09",
  "suggested_price": 67.23,
  "product_competiter": {
    "id": 3751,
    "product_id": 1,
    "competitor_id": 2,
    "price": 67.23
  }
}

产品关系 model

public function ProductCompetiter(){
       return $this->hasOne(ProductCompetiter::class)->orderBy('price', 'asc');
   }

基本上我想比较real_priceproduct_competiter.price 如果real_price大于product_competiter.price那么我只想显示结果。

谢谢

如果您经常使用此比较,您可以在Product model 中创建一个辅助方法,例如:

class Product extends Model
{
    // More of your code here...
    public function isCheaperThanCompetitor(): bool
    {
        return $this->price < $this->productCompetiter->price;
    }
}

有点跑题了,想给你一些技巧来让price浮动,比如:

class Product extends Model
{
    protected $casts = [
        'price' => 'float',
    ];
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM