【问题标题】:Laravel Eloquent question, trying to group results via a table not directly relatedLaravel Eloquent 问题,尝试通过不直接相关的表格对结果进行分组
【发布时间】:2021-03-28 22:09:24
【问题描述】:

我觉得有一种简单的方法可以做到这一点,但只是找不到它......我正在使用 Laravel 创建一个包含产品列表的商店。我的数据库中有 3 个表:

分类表 - ID, 名字

产品表 - ID, 类别 ID, 品牌标识, 姓名, 实时(布尔)

品牌表 - ID, 名字

在类别页面上,我想列出所有附加了实时产品的品牌。我觉得它应该是一个类别通过产品有很多品牌,但它就是不想工作。

还是我应该换一种方式?

任何帮助将不胜感激

【问题讨论】:

  • Products表的列不应该是category_id和brand_id吗?否则,您将需要指定键以继续使用您拥有的列名。你是如何定义这些关系的?
  • 你说得对,尼克,他们实际上是这样称呼的。将编辑问题:)

标签: php database laravel eloquent


【解决方案1】:

根据您的要求,使用 hasManyThrough 关系,您想通过产品模型列出类别模型的所有品牌,但您的表结构不正确。请参阅 laravel 文档:https://laravel.com/docs/8.x/eloquent-relationships#has-many-through

您可以更改您的表结构,或者如果您不适合这样做,那么您可以尝试使用 whereHas 从当前结构中获取所有具有实时产品的品牌,如下所示:

品牌型号:

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

拥有实时产品的品牌:

$brands_with_live_products = Brand::whereHas('products', 
function($q){
    $q->where('live', '==', 'true');
})->get();
// only brands that have live products will be selected

【讨论】:

  • 我得到了我想要的东西:code $brands = DB::table('brands') ->leftJoin('products', 'brands.id', '=' , 'products.brand_id') ->leftJoin('categories', 'categories.id', '=', 'products.category_id') ->select('brands.id', 'brands.name') ->where ('products.live', true) ->Where('categories.id', $category->id) ->groupBy('products.brand_id') ->orderBy('brands.name', 'Asc') - >get(); /code 只是认为会有更多的 Laravel 方式来做到这一点?
  • 这很棒!只需将内部查询稍微更改为 $q->where('live' , true) 但它比我的解决方法要干净得多!非常感谢:)
【解决方案2】:

$category->products->groupBy('brand.name') 这样简单的东西会给你一个按品牌分组的集合

更新:

$category->products()->where('live', true)->get()->groupBy('brand.name')

或者类似的东西

class Category extends Model
{
    use HasFactory;

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

    public function liveProducts()
    {
        return $this->products()
            ->where('live', true);
    }
}

// Then you can call 
$category->liveProducts->groupBy('brand.name');

【讨论】:

  • 他想选择所有拥有 live 产品的品牌,这意味着 live (boolean) 是真的
  • 也许我误读了 OP,但它还需要考虑类别,而不仅仅是任何具有实时产品的品牌
猜你喜欢
  • 2019-08-06
  • 2019-07-17
  • 2021-01-26
  • 2011-10-25
  • 1970-01-01
  • 1970-01-01
  • 2019-01-24
  • 1970-01-01
  • 2013-10-01
相关资源
最近更新 更多