laravel 5 : 4个以上表之间的可伸缩关系

laravel 5 : scalable relationship between more than 4 tables

我正在从事一个电子学习项目,想在 table 之间建立可扩展的关系,但一直停留在如何使用 eloquent 关系映射它们上。 我有 5 table

 1. boards : id, name(field names)
 2. standards: id, board_id, name
 3. subjects: id, board_id, standard_id, name
 4. chapters: id, board_id, standard_id, subject_id , name
 5. questionTypes: id, type(like MCQ, T/F, Fill in the blanks)
 6. questions: id,board_id, standard_id, subject_id, chapter_id, question_type_id, question 

结构描述

我正在使用 laravel 5 并且我是 eloquent 关系中的新手

您需要为每个 table 创建模型: php artisan make:model Board

注意: Laravel 知道要使模型复数化,这样模型板就变成了 Table 板。这也适用于像这样的词:Copy/copies,等

Artisan 还会为您创建的每个模型创建一个迁移文件。

在本次迁移中,您需要定义外键。

Schema::create('boards', function(Blueprint $table)
        {
            $table->increments('id');
            $table->timestamps();
        });


Schema::create('standards', function(Blueprint $table)
        {
            $table->increments('id');
            $table->integer('board_id')->unsigned();
            $table->timestamps();

            $table->foreign('board_id')->references('id')->on('boards')->onDelete('cascade');
        });

Schema::create('subjects', function(Blueprint $table)
        {
            $table->increments('id');
            $table->integer('board_id')->unsigned();
            $table->integer('standard_id')->unsigned();
            $table->timestamps();

            $table->foreign('board_id')->references('id')->on('boards')->onDelete('cascade');
            $table->foreign('standard_id')->references('id')->on('subjects')->onDelete('cascade');
        });

等...

并且在每个模型文件中,您定义关系:

<?php 

namespace App;

use Illuminate\Database\Eloquent\Model;

class Board extends Model {

    protected $fillable = [];

    public function standards()
    {
        return $this->hasMany('App\Standard');
    }

    public function subjects()
    {
        return $this->hasMany('App\Subject');
    }


    ...


}

在其他模型中:

<?php 

namespace App;

use Illuminate\Database\Eloquent\Model;

class Standard extends Model {

    protected $fillable = [];

    public function board()
    {
        return $this->belongsTo('App\Board');
    }


}


<?php 

namespace App;

use Illuminate\Database\Eloquent\Model;

class Subject extends Model {

    protected $fillable = [];

    public function board()
    {
        return $this->belongsTo('App\Board');
    }

    public function standard()
    {
        return $this->belongsTo('App\Standard');
    }

    ...


}

现在,在 Laravel 中,您可以执行以下操作:

Board::find(1)->subjectsSubject::find(4)->board

希望对您有所帮助!