繁体   English   中英

从目录laravel获取所有产品

[英]Getting all products from catalog laravel

我有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]);
    }


}

所以,问题是:如何通过它的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)

但我怎样才能在他的情况下得到他们?

首先,在Catalog模型中定义目录和产品之间的关系:

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

暂无
暂无

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

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