繁体   English   中英

Laravel雄辩的间接关系使用hasMany

[英]Laravel Eloquent indirect relation ship using hasMany

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

现在我的实际情况是我有一个具有许多产品类别的商店,每个产品类别都有许多产品,因此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');
  }
}
?>

您可以使用急切加载

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();

我还没有测试过,但是应该接近了……将其放入您的产品模型中:

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();
}

您可以在Controller中使用$products = Product::getProductsByShop(1);调用它$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;
    }
}

暂无
暂无

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

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