Neve12ende12
Neve12ende12

Reputation: 1194

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));

Upvotes: 1

Views: 1227

Answers (1)

Shynggys Kengessov
Shynggys Kengessov

Reputation: 379

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.

Upvotes: 1

Related Questions