【问题标题】:Laravel Eloquent double relation with conditionLaravel Eloquent 与条件的双重关系
【发布时间】:2017-03-21 08:29:40
【问题描述】:

我有以下数据的三个模型:

  1. 产品

    • 身份证
    • 姓名
    • 说明
  2. 变体

    • 身份证
    • 颜色
    • 类型
    • 私人
    • product_id
  3. 图片

    • 网址
    • variant_id

所以关系是:

  • 产品有很多变体
  • 变体有很多图像

我需要获取所有变体的集合,包括父产品,因为我还需要它的名称并包括与变体相关的图像,条件是(在变体上)->where('type', 'OPT ') 和 ->where('private', false)。

我尝试使用原始 SQL 查询来执行此操作,但我需要遍历刀片模板中的变体图像,因此我需要一个集合。如何在不运行太多查询的情况下将所有内容放在一起?

【问题讨论】:

    标签: database laravel eloquent relationship


    【解决方案1】:

    确保您的 Variant 模型上有这些关系:

    public function product()
    {
        return $this->belongsTo(Product::class);
    }
    
    public function images()
    {
        return $this->hasMany(Image::class);
    }
    

    那么你可以这样做:

    $collection = Variant::with('product', 'images')
        ->where('type', 'OPT')
        ->where('private', false)
        ->get();
    

    【讨论】:

      猜你喜欢
      • 2020-10-26
      • 2014-11-15
      • 2016-11-21
      • 1970-01-01
      • 2020-12-23
      • 2013-06-20
      • 2020-04-21
      • 2015-05-19
      • 2018-08-20
      相关资源
      最近更新 更多