两个模型可以在Laravel中使用同一张表吗

时间:2018-10-07 11:18:47

标签: laravel model eloquent

我有一个带有is_parent作为其外键链接的类别表,该表的类别ID在同一表中。现在我要创建关系类别hasMany子类别,并且该子类别属于一个类别。 这样我才能雄辩地访问。我怎么做?

这是我的表结构:

Schema::create('categories', function (Blueprint $table) {
    $table->increments('id');
    $table->string('category_name');
    $table->text('category_description')->nullabale();
    $table->string('category_image');
    $table->boolean('category_status');
    $table->integer('user_id')->unsigned();
    $table->boolean('is_parent');
    $table->timestamps();
    $table->index('user_id');
    $table->foreign('user_id')->references('id')->on('users');
});

1 个答案:

答案 0 :(得分:0)

您可以为同一张桌子创建2个模型,但您无需这样做。

这是您如何处理父>子关系:

Schema::create('categories', function (Blueprint $table) {
   $table->increments('id');
   $table->integer('parent_id')->unsigned()->nullable()->default(null);
   ...
});

对于模型内容:

class Category extends Model{
  ...
     public function parent(){
        return $this->belongsTo('App\Category','parent_id');
     }
     public function children(){
        return $this->hasMany('App\Category','parent_id');
     }
}

现在可以访问类别的子项:

$category = App\Category::find(1);
$subCategories = $category->children;

此方法的优点是您不需要两个单独的表,一个用于category,一个用于sub-categories,或两个模型,只需一个表,一个模型< / p>

相关问题