Как отобразить API продукта по категориям, используя laravel - PullRequest
0 голосов
/ 01 мая 2020

Мой ожидаемый JSON формат: enter image description here

Это мой ожидаемый JSON формат, у меня есть таблица продуктов вместе с таблицей, связанной с продуктами. Я хочу показывать товары в категориях. Таблица продуктов: enter image description here

Таблица категорий: enter image description here

Вот моя модель продукта:

    <?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Product extends Model
{
    /**
     * The attributes that aren't mass assignable.
     *
     * @var array
     */
    protected $guarded = ['id'];
    private $minimum_price;

    /**
     * Get the products image.
     *
     * @return string
     */
    public function getImageUrlAttribute()
    {
        if (!empty($this->image)) {
            $image_url = asset('/storage/img/product/' . $this->image);
        } else {
            $image_url = asset('/img/default.png');
        }
        return $image_url;
    }

    public function product_variations()
    {
        return $this->hasMany(\App\ProductVariation::class);
    }

    /**
     * Get the brand associated with the product.
     */
    public function brand()
    {
        return $this->belongsTo(\App\Brands::class);
    }

     /**
     * Get the unit associated with the product.
     */
    public function unit()
    {
        return $this->belongsTo(\App\Unit::class);
    }
    /**
     * Get category associated with the product.
     */
    public function category()
    {
        return $this->belongsTo(\App\Category::class);
    }
    /**
     * Get sub-category associated with the product.
     */
    public function sub_category()
    {
        return $this->belongsTo(\App\Category::class, 'sub_category_id', 'id');
    }


    /**
     * Get the brand associated with the product.
     */
    public function product_tax()
    {
        return $this->belongsTo(\App\TaxRate::class, 'tax', 'id');
    }

    /**
     * Get the variations associated with the product.
     */
    public function variations()
    {
        return $this->hasMany(\App\Variation::class);
    }

    /**
     * If product type is modifier get products associated with it.
     */
    public function modifier_products()
    {
        return $this->belongsToMany(\App\Product::class, 'res_product_modifier_sets', 'modifier_set_id', 'product_id');
    }

    /**
     * If product type is modifier get products associated with it.
     */
    public function modifier_sets()
    {
        return $this->belongsToMany(\App\Product::class, 'res_product_modifier_sets', 'product_id', 'modifier_set_id');
    }

    /**
     * Get the purchases associated with the product.
     */
    public function purchase_lines()
    {
        return $this->hasMany(\App\PurchaseLine::class);
    }

    public function images()
    {
        return $this->hasMany(ProductImage::class);
    }

    public function attributes()
    {
        return $this->hasMany(ProductAttribute::class);
    }

    public function attributesWithoutDefault()
    {
        return $this->hasMany(ProductAttribute::class)->where('attribute_id', '>', 4);
    }

    public function vendor_product()
    {
        return $this->hasMany(VendorProduct::class, 'product_id', 'id');
    }

    public function origin()
    {
        return $this->belongsTo(ProductOrigin::class);
    }

    public function defaultAttributes()
    {
        return $this->hasMany(ProductAttribute::class)->where('attribute_id', '<=', 4);
    }

    public function notes()
    {
        return $this->hasMany(ProductNote::class);
    }

    public function additionalCategory()
    {
        return $this->belongsTo(\App\Category::class, 'additional_category', 'id');
    }

    public function getAdditionalCategoryNameAttribute()
    {
        $additional_category = $this->additionalCategory;
        return $additional_category ? $additional_category->name : null;
    }

    public function industries()
    {
        return $this->belongsToMany(Industry::class, 'product_industries');
    }

    public function getCatalogUrlAttribute()
    {
        return asset('/uploads/'. constants('product_catalog_path') . '/' . $this->catalog_brusher);
    }

    public function getSpecSheetUrlAttribute()
    {
        return asset('/uploads/'. constants('product_spec_sheet_path') . '/' . $this->spec_sheet);
    }

    public function relatedProducts()
    {
        return $this->belongsToMany(Product::class, 'related_products', 'product_id', 'related_product_id');
    }

    private function setMinPrice()
    {
        if (is_null($this->minimum_price)) {
            $this->minimum_price = $this->vendor_product->min('price');
        }
        return $this->minimum_price;
    }

    public function getMinPriceAttribute()
    {
        return $this->setMinPrice();
    }

    public function getMinPriceVendorAttribute()
    {
        $min_price = $this->setMinPrice();
        if (is_null($min_price)) return null;

        $min_vendor_product = $this->vendor_product->firstWhere('price', $min_price);
        return Contact::find($min_vendor_product->vendor_id);
    }

    /**
     * Get the unit quantity associated with the product.
     */
    public function unitQuantity()
    {
        return $this->belongsTo(\App\UnitQuantity::class);
    }
}

1 Ответ

0 голосов
/ 01 мая 2020

вы должны присоединяться к одной и той же таблице более одного раза, каждый раз, когда вы присоединяетесь,

вы присоединяетесь с подходящим псевдонимом:

$list = Product::
leftJoin('categories as mainCategory','products.category_id','mainCategory.id')
->leftJoin('categories as subCategory','products.sub_category_id','subCategory.id')
->leftJoin('categories as additionalCategory','products.additional_category','additionalCategory.id')
->select(['products.*','mainCategory.name as mainCategoryName','subCategory.name as subCategoryName','additionalCategory.name as additionalCategoryName'])->get();

обратите внимание, что в вашем столбце «products.additional_category» должно быть названо

products.additional_category_id

см .: { ссылка }

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...