【问题标题】:Getting all products from catalog laravel从目录 laravel 获取所有产品
【发布时间】:2017-02-11 17:36:00
【问题描述】:

我有 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)

但是在我的情况下我怎样才能得到它们呢?

【问题讨论】:

    标签: php laravel laravel-5 eloquent


    【解决方案1】:

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

    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

    【讨论】:

    • 非常感谢!这正是我需要的(:
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-11-07
    • 1970-01-01
    • 2020-09-28
    • 2012-02-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多