我正在使用 Laravel 5.1。场景如下(此为示例,真实场景与此示例类似)
我有3个型号
- 大学
- 学生
- Teacher
一所学院可以有很多学生,但一个学生只能属于一所学院。
一所学院可以有多名教师,但一名教师只能属于一所学院。
我想在 laravel 中建立这些表之间的关系。
实现此目的的方法之一是放置一个学院_id学生和教师表上的外键。但就我而言,这个外键很多时候都会为空。因此,我不想在 3-4 个表中使用大部分为空值的单独列,而是想探索为 College 表建立多态关系的选项。
这是我尝试过的:laravel 文档(下面的链接)中给出的示例描述了一对多关系,而我的场景更多的是多对一关系。
http://laravel.com/docs/5.1/eloquent-relationships#polymorphic-relations http://laravel.com/docs/5.1/eloquent-relationships#polymorphic-relations
如示例中所示,College 表中包含 Collegeable_id 和 Collegeable_type 列无法满足我的要求,因为大学可以包含许多学生/教师,因此我创建了一个数据透视表:
Schema::create('collegeables', function (Blueprint $table) {
$table->integer('college_id')->unsigned();
$table->integer('collegeable_id')->unsigned();
$table->string('collegeable_type');
});
我有以下型号
学院模式:
namespace App;
use Illuminate\Database\Eloquent\Model;
class College extends Model
{
public function students()
{
return $this->morphedByMany('App\Student', 'collegeable');
}
}
学生型号:
namespace App;
use Illuminate\Database\Eloquent\Model;
class Student extends Model
{
public function college()
{
return $this->morphOne('App\Colleges', 'collegeable');
}
}
通过这种安排,我可以使用像这样的 College 模型实例来存储学生
$college = \App\College::find(1);
$student = new \App\Student;
$student->name = 'John Doe';
$college->students()->save($student);
但是,当我尝试使用下面指定的学生模型实例检索大学模型实例时,它给了我一个错误:-
public function index()
{
return \App\Student::find(1)->college;
}
SQLSTATE[42S22]:未找到列:1054 未知列“colleges.collegeable_id”
这是预料之中的,因为 morphOne 与表中的列一起工作,我想。
如果我将学生模型中的 morphOne 函数更改为 morphToMany,代码就会开始工作,并且我也能够检索值。但这使得这种关系成为多对多,这又不是我想要的。
所以我的问题是这样的:-
它们是我可以在学生模型中使用的 morphSomething 函数,以便能够检索学生大学的值,同时保持一对多的关系吗?
任何帮助将非常感激。谢谢。