簡體   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