2013-11-03 58 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; 
    } 
}