use Illuminate\Database\Eloquent\Relations\HasMany;
class Teacher extends Model {
public function students(): HasMany {
return $this->hasMany(Student::class);
}
}
学生模型
use Illuminate\Database\Eloquent\Relations\BelongsTo;
class Student extends Model {
//Relation below not define.
/* public function teacher(): BelongsTo {
return $this->belongsTo(Teacher::class);
} */
}
//each line below works fine, you can perform relationship related query
$teacher->students()->create([...]); // create students relation
$teacher->students; //lazy load students relation
Teacher::with('students')->paginate(); //eager load students relation
//each line below will throw 500 error as Inverse relation is not define
$student->teacher()->create([...]); // create teacher relation
$student->teacher; //lazy load teacher relation
Student::with('teacher')->paginate(); //eager load teacher relation
3条答案
按热度按时间oprakyz71#
并且
belongsTo
是一个one-to-many
,而不是many-to-many
。关于你的问题,你可以在任何定义它的地方访问关系,但除非你定义它,否则不能访问逆关系!
例如,如果您有教师和学生模型
教师模型
学生模型
c90pui9n2#
应用程序实际上并没有发生什么变化,只是如果您要访问透视表,您将无法从它调用任何关系。
eaf3rand3#
如果你正在创建透视表,你应该创建一个belongsToMany关系,它为你提供sync(),attach()方法。否则你可以简单地创建hasMany关系。你实际上在尝试做什么?