我有3张桌子:
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');
}
}
我通过存储库处理数据
示例:
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]);
}
}
所以,问题是:如何从目录中获取目录中的所有产品? 在原始的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 :(得分: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