Laravel 5.7从动态类别中获取所有产品并将其作为一个数据

时间:2019-01-15 08:47:49

标签: php laravel

我有2个数据库和2个模型, 这是模型

Category.php

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Category extends Model
{
    protected $guarded = [];

    public function sub_categories()
    {
        return $this->hasMany(Category::class, 'parent_id', 'id');
    }

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

    public function all_products()
    {
        return $this->hasManyThrough(\App\Product::class, \App\Category::class, 'parent_id', 'category_id', 'id', 'id');
    }
}

Product.php

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Product extends Model
{
    public function category()
    {
        return $this->belongsTo(\App\Category::class);
    }
}

产品表

Schema::create('products', function (Blueprint $table) {
    $table->increments('id');
    $table->unsignedInteger('category_id');
    $table->string('name');
    $table->string('slug')->unique();
    $table->text('description');
    $table->text('galleries');
    $table->timestamps();

    $table->foreign('category_id')->references('id')->on('categories')->onDelete('cascade');
});

类别表

Schema::create('categories', function (Blueprint $table) {
    $table->increments('id');
    $table->unsignedInteger('parent_id')->nullable();
    $table->string('name');
    $table->string('slug')->unique();
    $table->text('description');
    $table->timestamps();

    $table->foreign('parent_id')->references('id')->on('categories');
});

我遇到的问题是,如果选择了父类别,我想获取所有产品。所以说我有这个类别和产品

Category 1 <-- parent category with 3 products      \
    Category 1-a <-- child category with 1 products  \ 13 products in total
    Category 1-b <-- child category with 2 products  /
    Category 1-c <-- child category with 7 products /
Category 2 <-- parent category
    Category 2-a <-- child category
    Category 2-b <-- child category
    Category 2-c <-- child category

因此,我在all_products()类别模型中创建了hasManyThrough()关系,但是如果我选择了父类别(只有3个商品,但将显示所有商品),则无法获得所有商品也是孩子们。

那么如何用雄辩的方式获得所有产品呢?所以我可以只用$category->all_products()来称呼它吗?

谢谢

0 个答案:

没有答案