我正在使用laravel 5.1 . 场景如下(这是一个例子 . 真实情况类似于这个例子)
我有3个型号
-
大学
-
学生
-
老师
一所大学可以有很多学生,但学生只能拥有一所大学 .
一所大学可以有很多老师,但老师只能拥有一所大学 .
我想在laravel中 Build 这些表之间的关系 . 其中一种方法是在Students and Teachers表中放置一个college_id外键 . 但就我而言,这个外键很多次都会为空 . 因此,我想要探索具有大学表的多态关系的选项,而不是在3-4个表中具有大多数空值的单独列 .
This is what I tried: laravel文档中给出的示例(下面的链接)描述了一对多关系,而我的场景更多的是多对一关系 .
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);
但是当我尝试使用下面指定的学生模型实例检索College模型实例时,它会给我一个错误: -
public function index()
{
return \App\Student::find(1)->college;
}
SQLSTATE [42S22]:找不到列:1054未知列'colleges.collegeable_id'
这是一种预期,因为morphOne适用于我想象的表中的列 . 如果我将学生模型中的morphOne函数更改为morphToMany,代码将开始工作,我也能够检索值 . 但这使得这种关系成为许多人,而这又不是我想要的 .
So my question is this:- Is their a morphSomething function I can use in the student model to be able to retrieve values for the student's college while maintaining the relationship as a one-to-many?
任何帮助将非常感激 . 谢谢 .
1 回答
这里没有理由使用多态关系 . 相反,只需在
students
和teachers
表上为colleges
表添加外键即可 . 像这样:然后你的模型可以使用
belongsTo()
和hasMany()
关系,如下所示:多态一对多关系与此关系相反,在这种关系中,您有一个只能与单个记录相关的模型,但该记录可以是许多不同的模型 .
编辑:为了进一步解释为什么这里不需要多态关系,让我们来看看它需要什么 . 假设你有一个简单的CRM风格的网站 . 有客户和项目,您希望对两者都有评论 . 在这种情况下,您将使注释成为多态关系,因为注释属于单个客户或单个项目,但不是两者 .
你的关系恰恰相反 . 在您的情况下,学生和教师属于大学 . 如果你要遵循上一个例子的模式,那么一所大学就属于一个学生或老师 .