2013-11-03 55 views
0

我的问题本质上是这样的,我有一个间接引用模型使用相关模型的问题,就像'模型A'有很多'模型B'和'模型B'一样许多'模型C',所以基本上这将是'模型A'有许多'模型C',但我不知道如何使用hasMany来联系他们。Laravel雄辩的间接关系船使用hasMany

现在我的实际情况是我店里有很多产品类别,每个产品类别都有很多产品,所以Shop-> ProductCategory是使用hasMany相关的,以及ProductCategory->使用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'); 
    } 
} 
?> 

回答

0

您可以使用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(); 
+0

在这种情况下,我将无法获得下店铺的所有产品,我将不得不遍历每个类别获得的所有产品。 而不是商店 - >产品,我将不得不编写一个循环来获取所有产品? –

+0

检查答案中给出的热切加载链接,有一个例子,你可以循环。 –

0

我没有测试过这一点,但它应该是关闭...把这个在您的产品型号:

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