【问题标题】:Laravel Eloquent indirect relation ship using hasManyLaravel Eloquent 间接关系使用 hasMany
【发布时间】:2013-11-14 05:13:13
【问题描述】:

我的问题本质上是这样的,我有一个使用相关模型间接引用模型的问题,例如“模型 A”有很多“模型 B”而“模型 B”有很多“模型 C”,所以本质上,“模型 A”有很多“模型 C”,但我不知道如何使用 hasMany 将它们关联起来。

现在我的实际情况是我有一个Shop有很多Product Categories,每个Product category有很多Product,所以Shop->ProductCategory用hasMany关联,ProductCategory->Products用hasMany关联,我想关联商店和产品,而无需在产品表中创建新列来存储商店 ID。

这是我的模型

/* Models */
// Shop.php
<?php
class Shop extends Eloquent {
  public function productCategories() {
    return $this->hasMany('ProductCategory');
  }
}
?>
//Product.php
<?php
class Product extends Eloquent {
  public function productCategory() {
    return $this->belongsTo('ProductCategory');
  }
}
?>
//ProductCategory.php
<?php
class ProductCategory extends Eloquent {
  public function shop() {
    return $this->belongsTo('Shop');
  }
  public function products() {
    return $this->hasMany('Product');
  }
}
?>

【问题讨论】:

    标签: php laravel eloquent


    【解决方案1】:

    您可以使用Eager Loading

    class Shop extends Eloquent {
        public function productCategories() {
            return $this->hasMany('ProductCategory');
        }
    }
    
    class ProductCategory extends Eloquent {
        public function products() {
            return $this->hasMany('Product');
        }
    }
    
    $shop = Shop::with( array( 'productCategories', 'productcategory.products' ) )->get();
    

    【讨论】:

    • 在这种情况下,我将无法获得 shop 下的所有产品,我必须遍历每个类别才能获得所有产品。而不是 shop->products ,我将不得不编写一个循环来让所有产品都正确?
    • 检查答案中给出的急切加载链接,有一个例子,你可以循环。
    【解决方案2】:

    我还没有测试过这个,但应该很接近......把这个放在你的产品模型中:

    public static function getProductsByShop($shop_id)
    {
        return DB::table('shops')
            ->where('shops.id','=',$shop_id)
            ->join('categories', 'categories.shop_id', '=', 'shops.id')
            ->join('products', 'products.category_id', '=', 'categories.id')
            ->select(DB::raw('products.*'))
            ->get();
    }
    

    您可以在控制器中使用$products = Product::getProductsByShop(1); 调用它

    然后你可以遍历它

    foreach($products as $product)
    {
        echo $product->name;
    }
    

    但是,RCV 的方法在性能上会更好,因为您只会查询您需要的内容。我的方法将查询所有内容,然后从您正在寻找的商店中提取行。 RCV 的方法只是迭代时的额外步骤......

    foreach($shop->productCategories as $cat)
    {
        foreach($cat->products as $product)
        {
            echo $product->name;
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2016-03-17
      • 2014-10-29
      • 2015-12-22
      • 1970-01-01
      • 2021-11-06
      • 1970-01-01
      • 1970-01-01
      • 2019-11-12
      • 2020-03-12
      相关资源
      最近更新 更多