gpt4 book ai didi

php - 拉拉维尔 5 : scalable relationship between more than 4 tables

转载 作者:行者123 更新时间:2023-11-29 22:17:42 25 4
gpt4 key购买 nike

我正在开发一个电子学习项目,希望在表之间建立可扩展的关系,但一直专注于如何使用 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

结构描述

  • boards 代表学习委员会、州委员会和所有委员会
  • 标准代表类别示例:1st 2nd 等
  • 科目就像数学科学
  • 章节就像数学学科的数字系统
  • question_types 代表此项目中的问题类型,我有 3 种类型的问题,但可以更多
  • 问题表包含取决于boardstandardsubject的章节的所有问题。

我正在使用 Laravel 5,而且我是 Eloquent 关系中的新手

最佳答案

您需要为每个表创建模型:php artisan make:模型板

注意:Laravel 知道对模型进行复数化,以便模型板成为表格板。这也适用于以下单词:复制/副本等。

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

希望这有帮助!

关于php - 拉拉维尔 5 : scalable relationship between more than 4 tables,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31049680/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com