如何在laravel中的表内创建关系?

问题描述

我需要在表中创建一个关系。我在下面附上了我的桌子。

enter image description here

这是我的类别模型。

class Category extends Model
{
    public function products()
    {
       return $this->hasMany(Product::class);
    }

    public function categories_id() {
        return $this->hasMany('category_id','parent_id');
    }
    public function parent_id() {
        return $this->hasMany('category_id','parent_id');
    }
}

在这里如何关联category_id和parent_id?

这是我的 categories_table

 public function up()
    {
       Schema::create('categories',function (Blueprint $table)
        {
        $table->bigIncrements('id');
        $table->unsignedBigInteger('parent_id')->nullable();
        $table->string('cat_name')->nullable();
        $table->string('cat_image_path')->nullable();
        $table->timestamps();
         });
    }

解决方法

您可以尝试以下设置:

public function parent()
{
    return $this->belongsTo(self::class);
    // uses `parent_id` to find the parent by 'id'
}

public function children()
{
    return $this->hasMany(self::class,'parent_id');
    // finds other records where their 'parent_id' is the parent's 'id'
}

$category = Category::find(...);

$parent = $category->parent;
$children = $category->children;

此外,您的架构中没有category_id字段。

关于这些关系的所有信息都在文档中。

Laravel 7.x Docs - Eloquent - Relationships - One To Many hasMany

Laravel 7.x Docs - Eloquent - Relationships - One To Many (Inverse) belongsTo

Laravel 7.x Docs - Eloquent - Relationships - Relationship Methods vs Dynamic Properties

相关问答

依赖报错 idea导入项目后依赖报错,解决方案:https://blog....
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下...
错误1:gradle项目控制台输出为乱码 # 解决方案:https://bl...
错误还原:在查询的过程中,传入的workType为0时,该条件不起...
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct...