[英]Laravel-Many-to-one Polymorphic relationship
我正在使用 laravel 5.1。 場景如下(這是一個例子,真實場景和這個例子類似)
我有 3 個模型
一所大學可以有很多學生,但一個學生只能屬於一所大學。
一個學院可以有很多老師,但一個老師只能屬於一所學院。
我想在 laravel 中建立這些表之間的關系。 一種方法是在學生和教師表上放置一個college_id外鍵。 但就我而言,這個外鍵很多時候都是 null 。 因此,我不想在 3-4 個表中分別使用 null 值,而是想探索為 College 表提供多態關系的選項。
這是我嘗試過的: laravel 文檔(下面的鏈接)中給出的示例描述了一對多的關系,而我的場景更多的是多對一的關系。
http://laravel.com/docs/5.1/eloquent-relationships#polymorphic-relations
如示例中所示,College 表上的collegeable_id 和collegeable_type 列無法滿足我的要求,因為大學可以包含許多學生/教師,因此我創建了一個pivot 表:
Schema::create('collegeables', function (Blueprint $table) {
$table->integer('college_id')->unsigned();
$table->integer('collegeable_id')->unsigned();
$table->string('collegeable_type');
});
我有以下型號
學院 Model:
namespace App;
use Illuminate\Database\Eloquent\Model;
class College extends Model
{
public function students()
{
return $this->morphedByMany('App\Student', 'collegeable');
}
}
學生 Model:
namespace App;
use Illuminate\Database\Eloquent\Model;
class Student extends Model
{
public function college()
{
return $this->morphOne('App\Colleges', 'collegeable');
}
}
通過這種安排,我可以像這樣使用 College model 實例來存儲學生
$college = \App\College::find(1);
$student = new \App\Student;
$student->name = 'John Doe';
$college->students()->save($student);
但是,當我嘗試使用如下指定的學生 model 實例檢索大學 model 實例時,它給了我一個錯誤:-
public function index()
{
return \App\Student::find(1)->college;
}
SQLSTATE [42S22]:找不到列:1054 未知列 'colleges.collegeable_id'
這是預期的,因為 morphOne 我想可以處理表中的列。 如果我將 Student Model 中的 morphOne function 更改為 morphToMany,則代碼開始工作,我也可以檢索值。 但這使這種關系成為多對多的關系,這又不是我想要的。
所以我的問題是:- 他們是 morphSomething function 我可以在學生 model 中使用,以便能夠檢索學生大學的值,同時保持一對多的關系嗎?
任何幫助將非常感激。 謝謝。
這里沒有理由使用多態關系。 相反,只需在students
和teachers
表上的colleges
表中添加外鍵。 像這樣:
colleges
id
name
teachers
id
name
college_id
students
id
name
college_id
然后,您的模型可以使用belongsTo()
和hasMany()
關系,如下所示:
class College extends Model {
public function students() {
return $this->hasMany(App\Student::class);
}
public function teachers() {
return $this->hasMany(App\Teacher::class);
}
}
class Teacher extends Model {
public function colleges() {
return $this->belongsTo(App\College::class);
}
}
class Student extends Model {
public function colleges() {
return $this->belongsTo(App\College::class);
}
}
多態一對多關系與此關系相反,在這種關系中,您有一個只能與單個記錄關聯的模型,但是該記錄可以是許多不同的模型。
編輯:為了進一步解釋為什么這里不需要多態關系,讓我們看一下它在哪里需要。 假設您有一個簡單的CRM風格的網站。 有“客戶”和“項目”,並且您想對兩者都有評論。 在這種情況下,您將使注釋成為多態關系,因為注釋屬於單個客戶或單個項目,但不能同時屬於兩者。
您的關系正好相反。 在您的情況下,學生和教師屬於一所大學。 如果您遵循前面示例的模式,則一所大學將屬於一個學生或老師。
我也有類似的需求,並設法以另一種方式即興創作,利用了 morph 的表格結構。
你需要一個可大學的 class 是 Pivot ( https://laravel.com/docs/9.x/eloquent-relationships-modelsintermediate )
然后是魔法:
public function college(){
return $this->hasOneThrough(Colleges::class,
Collegeable::class,
'collegeable_id',
'id',
'id',
'college_id',
);
}
在可大學Pivot class 上:
namespace App\Models;
use Illuminate\Database\Eloquent\Relations\Pivot;
class Collegeable extends Pivot
{
protected $table = 'collegeables';
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.