【问题标题】:Laravel Eloquent - method to obtain grandchildren's data from GrandParentsLaravel Eloquent - 从 GrandParents 获取孙子数据的方法
【发布时间】:2020-11-30 10:58:18
【问题描述】:

我正在做电子商务网站,我有以下关系:

祖父母:类别(id、姓名)
父母:品牌(id、姓名、category_id)
儿童:产品(id、name、brand_id)

示例: 智能手机 (类别) -> iPhone (品牌) -> iPhone 12、iPhone 12 Pro、iPhone 12 Pro Max (产品)
我想从 Category likes 中获得所有上述 iPhone 12

$iPhone = App\Category::find(1)->brands->where('name','iPhone')->toArray()

感谢您的帮助

【问题讨论】:

  • 使用 hasManythrough 关系

标签: laravel laravel-5 eloquent


【解决方案1】:

获取“智能手机”类别的“iPhone”品牌的所有产品


$iphones = Category::whereName('Smartphone')
    ->with(['brands' => function($query){
        $query->with('products')->whereName('iPhone');
    })
    ->get();

【讨论】:

    【解决方案2】:

    试试这个查询

     $iPhones = App\Category::whereHas('brands', function ($query)
            {
                $query->where('name','iPhone');
            })->get();
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-03-20
      • 2021-12-10
      • 1970-01-01
      • 2021-12-07
      • 1970-01-01
      • 1970-01-01
      • 2020-10-08
      • 2016-09-09
      相关资源
      最近更新 更多