2017-02-10 49 views
1

我有3個表:讓所有的產品從目錄laravel

product 
*id 
category_id 
name 
... 

category 
*id 
catalog_id 
name 
... 

catalog 
*id 
name 
... 

和3款

class Catalog extends Model 
{ 
    public function category() 
    { 
     return $this->hasMany('App\Category'); 

    } 
} 

class Category extends Model 
{ 
    public function product() 
    { 
     return $this->hasMany('App\Product'); 

    } 

    public function catalog() 
    { 
     return $this->belongsTo('App\Catalog'); 
    } 
} 

class Product extends Model 
{ 
    public function category() 
    { 
     return $this->belongsTo('App\Category'); 

    } 
} 

我通過使用數據回購協議itories

例如:

abstract class Repository 
{ 
    protected $model = false; 

    public function get($select = '*',$where = false, $take = false) 
    { 
     $builder = $this->model->select($select); 

     if($where) 
     { 
      $builder->where($where); 
     } 

     if($take) 
     { 
      $builder->take($take); 
     } 

     return $builder->get(); 
    } 
} 

class ProductsRepository extends Repository 
{ 

    public function __construct(Product $products) 
    { 
     $this->model = $products; 
    } 

    public function getNewProducts() 
    { 
     return $this->get('*',['is_recommended' => 1],Config::get('settings.recommended_products_count')); 
    } 

    public function getProductsFromCategory($category_id) 
    { 
     return $this->get('*',['category_id' => $category_id]); 
    } 


} 

所以,問題是:如何可以得到所有產品目錄由它的id?在原始的SQL 它會看起來像:

select * from products 
    join categories 
     on categories.id=products.category_id 
    join catalogs 
     on catalogs.id=categories.catalog_id 
where(catalogs.id=1) 

,但我怎樣才能讓他們在我的情況?

回答

0

首先,定義目錄和產品之間的關係在目錄型號:

public function products() 
{ 
    return $this->hasManyThrough('App\Product', 'App\Category', 'catalog_id', 'category_id', 'id'); 
} 

現在,你應該能夠得到所有產品的定目錄有:

$products = Catalog::with('products')->find($id)->products; 

你可以瞭解更多關於has-many-through這裏關係:https://laravel.com/docs/5.4/eloquent-relationships#has-many-through

+0

非常感謝你!這很重要,我需要(: – Ronald