Database 在laravel中使用类别名称和子类别名称获取产品名称

Database 在laravel中使用类别名称和子类别名称获取产品名称,database,laravel,tree,Database,Laravel,Tree,我需要与产品名称的类别名称,我有两个数据库类别和prodcuts表,我想得到有关或与相关类别的参考产品 例如:- 类别和子类别与列表您需要建立多对多关系,因为每个产品可以有多个类别,并且每个类别可以关联到多个产品 Laravel文档相当不错,您可以查看: 假设您的型号是产品和类别,您可以执行以下操作: 在Product.php类中: public function categories() { return $this->belongsToMany('App\Category');

我需要与产品名称的类别名称,我有两个数据库类别和prodcuts表,我想得到有关或与相关类别的参考产品 例如:-


类别和子类别与列表

您需要建立多对多关系,因为每个产品可以有多个类别,并且每个类别可以关联到多个产品

Laravel文档相当不错,您可以查看:

假设您的型号是
产品
类别
,您可以执行以下操作:

Product.php
类中:

public function categories() {
    return $this->belongsToMany('App\Category');
}
public function products() {
    return $this->belongsToMany('App\Product');
}
在您的
Category.php
类中:

public function categories() {
    return $this->belongsToMany('App\Category');
}
public function products() {
    return $this->belongsToMany('App\Product');
}
现在,您需要在DB中创建表来支持该关系(在多个关系中,该表称为
pivot

创建类似于以下内容的新迁移:

/**
 * Run the migrations.
 *
 * @return void
 */
public function up()
{
    Schema::create('category_product', function (Blueprint $table) {

        $table->integer('category_id')->unsigned()->index();
        $table->foreign('category_id')->references('id')->on('categories');
        $table->integer('product_id')->unsigned()->index();
        $table->foreign('product_id')->references('id')->on('products');
    });
}

/**
 * Reverse the migrations.
 *
 * @return void
 */
public function down()
{
    Schema::dropIfExists('category_product');
}
现在,您可以非常简单地获得产品的类别:

$product->categories; // You get a collection of categories
$product->categories(); // You get the query if you need to add some filters
同样,您可以通过以下方式获得特定类别的所有产品:

$category->products;
要向您的产品添加类别,您可以通过多种方式进行,其中包括:

$product->categories()->attach($category_id);
$product->categories()->sync([$category_id1, $category_id2, ..]);

有关特定需求的更多详细信息,请阅读我上面链接的文档

到目前为止您尝试了什么?模型中有关系吗?欢迎使用堆栈溢出。请访问帮助中心并阅读。