Показать продукт на основе выбранной категории в Laravel 5.8? - PullRequest
2 голосов
/ 07 октября 2019

Приведенный ниже код представляет собой список моих категорий (product_categories), списка продуктов (products) и категорий, назначенных продуктам (product_selected_categories).

Я хочу отобразить свой продуктвместе с категорией, к которой он был добавлен. Я пытаюсь сделать это, используя следующий код:

Product::findOrFail($id)

Но этот код не работает. Код отображает только продукт без информации о категории, к которой принадлежит продукт.

Как это исправить?
Мой проект в Laravel 5.8.

  1. Миграция
Schema::create('product_categories', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->bigInteger('company_id')->unsigned();
            $table->foreign('company_id')->references('id')->on('companies')->onDelete('cascade');
            $table->char('enable', 1)->default(0);
            $table->string('name', 85)->nullable();
            $table->string('url_address', 160);
            $table->integer('level')->default(0);
            //$table->bigInteger('parent_id')->default(0);
            //$table->bigInteger('parent_id')->nullable();
            $table->unsignedBigInteger('parent_id')->nullable();
            $table->foreign('parent_id')->references('id')->on('product_categories')->onDelete('cascade');
            $table->bigInteger('number')->default(0);
            $table->timestamps();
            $table->engine = "InnoDB";
            $table->charset = 'utf8mb4';
            $table->collation = 'utf8mb4_unicode_ci';
        });

Schema::create('products', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->bigInteger('company_id')->unsigned();
            $table->foreign('company_id')->references('id')->on('companies')->onDelete('cascade');
            //$table->bigInteger('category_id')->unsigned();
            //$table->foreign('category_id')->references('id')->on('product_categories');
            $table->smallInteger('id_delivery_vat')->unsigned();
            $table->foreign('id_delivery_vat')->references('id')->on('vat');
            $table->smallInteger('id_product_vat')->unsigned();
            $table->foreign('id_product_vat')->references('id')->on('vat');
            $table->bigInteger('id_producer')->unsigned();
            //$table->foreign('id_producer')->references('id')->on('product_producers');
            $table->string('name', 120)->nullable();
            $table->string('qr_code', 120)->nullable();
            $table->string('oe_code', 120)->nullable();
            $table->char('enable', 1)->default(0);
            $table->char('promo', 1)->default(0);
            $table->longText('description')->nullable();
            $table->decimal('product_price', 9, 2)->default(0);
            $table->decimal('promo_product_price', 9, 2)->default(0);
            $table->decimal('product_delivery_price', 9, 2)->default(0);
            $table->unsignedInteger('quantity')->default(0);
            $table->string('url_address', 160);
            $table->timestamps();
            $table->engine = "InnoDB";
            $table->charset = 'utf8mb4';
            $table->collation = 'utf8mb4_unicode_ci';
        });

Schema::create('product_selected_categories', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->bigInteger('category_id')->unsigned()->index();
            $table->foreign('category_id')->references('id')->on('product_categories');
            $table->bigInteger('subcategory1_id')->default(0);
            $table->bigInteger('parent_subcategory1_id')->default(0);
            $table->bigInteger('subcategory2_id')->default(0);
            $table->bigInteger('parent_subcategory2_id')->default(0);
            $table->bigInteger('subcategory3_id')->default(0);
            $table->bigInteger('parent_subcategory3_id')->default(0);
            $table->bigInteger('subcategory4_id')->default(0);
            $table->bigInteger('parent_subcategory4_id')->default(0);
            $table->bigInteger('subcategory5_id')->default(0);
            $table->bigInteger('parent_subcategory5_id')->default(0);
            $table->bigInteger('subcategory6_id')->default(0);
            $table->bigInteger('parent_subcategory6_id')->default(0);
            $table->bigInteger('subcategory7_id')->default(0);
            $table->bigInteger('parent_subcategory7_id')->default(0);
            $table->bigInteger('subcategory8_id')->default(0);
            $table->bigInteger('parent_subcategory8_id')->default(0);
            $table->bigInteger('subcategory9_id')->default(0);
            $table->bigInteger('parent_subcategory9_id')->default(0);
            $table->bigInteger('product_id')->unsigned()->index();
            $table->foreign('product_id')->references('id')->on('products');
        });         
Модели
class Product extends Model
{
    use scopeActiveTrait;

    protected $fillable = ['company_id', 'id_delivery_vat', 'id_product_vat', 'id_producer', 'name', 'qr_code', 'oe_code', 'enable', 'promo', 'description', 'product_price', 'promo_product_price', 'product_delivery_price', 'quantity', 'url_address'];
    protected $quarded = ['id'];
    public $timestamps = true;

    public function categories()
    {
        return $this->belongsToMany(Category::class, 'product_selected_categories', 'product_id', 'category_id');
    }
}

class ProductCategory extends Model
{
    use scopeActiveTrait;

    protected $guarded = ['id'];
    protected $fillable = ['company_id', 'enable', 'name', 'url_address', 'level', 'parent_id', 'number'];
    public $timestamps = true;
    //protected $table = 'products_category';

    public function parent()
    {
        return $this->belongsTo('App\ProductCategory', 'parent_id', 'id');
    }

    public function children()
    {
        return $this->hasMany('App\ProductCategory', 'id', 'parent_id');
    }

    public function products()
    {
        return $this->belongsToMany(Product::class, 'product_selected_categories', 'category_id', 'product_id');
    }
}

class ProductSelectedCategory extends Model
{
    protected $quarded = ['id'];
    protected $fillable = ['subcategory1_id', 'parent_subcategory1_id', 'category_id', 'subcategory2_id', 'parent_subcategory2_id', 'subcategory3_id', 'parent_subcategory3_id', 'subcategory4_id', 'parent_subcategory4_id', 'subcategory5_id', 'parent_subcategory5_id', 'subcategory6_id', 'parent_subcategory6_id', 'subcategory7_id', 'parent_subcategory7_id', 'subcategory8_id', 'parent_subcategory8_id', 'subcategory9_id', 'parent_subcategory9_id', 'product_id' ];
    public $timestamps = false;
} 

Ответы [ 3 ]

1 голос
/ 08 октября 2019

Если вы знаете , что вам потребуются категории продуктов, вы можете быстро загрузить связанные модели, используя функцию with() QueryBuilder:

$product = Product::with('categories')->findOrFail($id);

Если вам необходимо загрузить несколько отношений, вы можете передать массив в with():

$product = Product::with(['categories', ...])->findOrFail($id);

Если, однако, вы может не потребоваться нужны категории продуктов, вы можете лениво загружать категории с помощью функции load():

$product = Product::findOrFail($id);

// ... some time later you end up needing the Categories...

$product->load('categories');

Здесь снова вы можете передать массивload() при необходимости:

$product->load(['categories', ...]);
0 голосов
/ 08 октября 2019

Другим вариантом, помимо перечисленных выше, будет определение свойства $with для вашей модели Product:

class Product extends Model
{
  use scopeActiveTrait;

  protected $fillable = ['company_id', 'id_delivery_vat', 'id_product_vat', 'id_producer', 'name', 'qr_code', 'oe_code', 'enable', 'promo', 'description', 'product_price', 'promo_product_price', 'product_delivery_price', 'quantity', 'url_address'];
  protected $quarded = ['id'];
  public $timestamps = true;

  protected $with = ['categories'];
  ...
}

Это еще один способ использовать готовую загрузку. Его следует использовать, только если вы знаете, что всякий раз, когда вы загружаете продукт (или продукты), вам всегда нужны категории каждого загруженного продукта. (см. «Готовая загрузка по умолчанию» здесь )

0 голосов
/ 08 октября 2019

Вы можете загрузить отношение следующим образом:

Product::findOrFail($id)->with('categories');
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...