From 470ae933b0bff31117d5a5d32d59953269bb5dc7 Mon Sep 17 00:00:00 2001 From: Matt Huntington Date: Fri, 11 Jan 2019 10:57:32 -0500 Subject: [PATCH] alter person model --- Nested_Models.md | 34 ++++++++++++++++++++++++++++++++++ 1 file changed, 34 insertions(+) diff --git a/Nested_Models.md b/Nested_Models.md index e111ef6..e6e0a44 100644 --- a/Nested_Models.md +++ b/Nested_Models.md @@ -58,3 +58,37 @@ UPDATE people SET home_id = 2 WHERE id = 4; ``` The previous code will find the row with an `id` of 4 and set the `home_id` column to 2. + +## Update the Person model + +First, let's add the functionality to allow the `Person` class to have an optional `home_id`: + +```php +class Person { + public $id; + public $name; + public $age; + public function __construct($id, $name, $age, $home_id = null) { + $this->id = $id; + $this->name = $name; + $this->age = $age; + if($home_id){ + $this->home_id = $home_id; + } + } +} +``` + +Now we can create a Person like we did before without a home id: + +```php +$new_person = new Person(1, "Bob", 23); +``` + +Or with it: + +```php +$new_person = new Person(1, "Bob", 23, 7); +``` + +If no 4th parameter is specified in `new Person`, `$home_id` in the constructor will be `null`, and the `if` statement will not run. If it is specified, then the `if` statement will run and set `$this->home_id`.