简体   繁体   中英

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. 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. 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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