简体   繁体   English

使用一对多关系为对象建模(PHP)

[英]Modeling an Object with one-to-many relationships (PHP)

I am trying to force myself to be consistent when modeling objects, but I'm just not sure what the best way is to create a class that has one-to-many relationships. 我试图强迫自己在建模对象时保持一致,但是我不确定最好的方法是创建具有一对多关系的类。

For example, lets say I have two tables in a database called Projects & Notes. 例如,假设我在一个名为Projects&Notes的数据库中有两个表。 A note can only belong to one project and a project can have many notes. 一个注释只能属于一个项目,一个项目可以有多个注释。 Would the following be a good (best) way to model my project class? 以下是对项目类进行建模的一种好方法(最佳方法)吗? Or should the notes just be set to a separate variable in the controller and never be a property of project? 还是应该在控制器中将注释设置为单独的变量,而不是项目的属性?

class Project extends BaseModel{
  $id //string
  $description //string
  $notes //array of note objects
}

class Note extends BaseModel{
  $id //string
  $text//string
}

//In a Controller Class
$project = new Project();
$noteArray = new Note();

//Set the note property of project equal to an array of note objects
$project->setNotes($noteArray->findNotes($project->id));

I think there should be one more property in Note model that will reference to the Project model. 我认为Note模型中应该还有一个属性可以引用Project模型。 Identificators of model MUST be an integer type 模型的标识符必须是整数类型

class Note extends BaseModel{
  $id //string
  $text//string
  $project_id //int
}

So when you add a project, say it, with ID=5, You can add Notes with project_id = 5. And it will be one-to-many relatoionship. 因此,当您添加一个ID = 5的项目时,您可以添加project_id = 5的Notes。这将是一对多的关系。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM