OneToOne relation

$ php artisan make:model Address -m

migration file

{
        Schema::create('addresses', function (Blueprint $table) {
            $table->increments('id');
            $table->integer('user_id')->unsigned()->nullable();
            $table->string('name');
            $table->timestamps();
        });
    }

$ php artisan migrate

User.php

public function address(){
        return $this->hasOne('App\Address');
    }

//data挿入
mysql> use onetoone;
Reading table information for completion of table and column names
You can turn off this feature to get a quicker startup with -A

Database changed
mysql> show tables;
+——————–+
| Tables_in_onetoone |
+——————–+
| addresses |
| migrations |
| password_resets |
| users |
+——————–+
4 rows in set (0.00 sec)

mysql> insert into users (name, email, password) values (‘peter’, ‘peter@gmail’, ‘1234’);
Query OK, 1 row affected (0.00 sec)

Address.php

class Address extends Model
{
    //
    protected $fillable = [
    	'name'
    ];
}

route.php

Route::get('/insert', function(){

	$user = User::findOrFail(1);
	$address = New Address(['name'=>'1234 Huston av NY NY 11218']);
	$user->address()->save($address);
});

mysql> select * from addresses;
+—-+———+—————————-+———————+———————+
| id | user_id | name | created_at | updated_at |
+—-+———+—————————-+———————+———————+
| 1 | 1 | 1234 Huston av NY NY 11218 | 2019-12-08 04:19:29 | 2019-12-08 04:19:29 |
+—-+———+—————————-+———————+———————+
1 row in set (0.00 sec)

$user->save();のところを、hasOneでは$user->address()->save($address);って書くんだ。I aint know what’s going on inside.

Route::get('/update', function(){

	$address = Address::where('user_id', 1)->first();

	$address->name = "4532 Updated new address";
	$address->save();
});

mysql> select * from addresses;
+—-+———+—————————+———————+———————+
| id | user_id | name | created_at | updated_at |
+—-+———+—————————+———————+———————+
| 1 | 1 | 4532 Updated new address | 2019-12-08 04:19:29 | 2019-12-08 04:39:56 |
| 2 | 1 | 1234 Tokyo av NY NY 11218 | 2019-12-08 04:28:09 | 2019-12-08 04:28:09 |
+—-+———+—————————+———————+———————+
2 rows in set (0.00 sec)

updateは、対象のレコードを選択してsave();

read

Route::get('/read', function(){
	$user = User::findOrFail(1);
	return $user->address->name;	
});

delete

Route::get('/delete', function(){

	$user = User::findOrFail(1);

	$user->address()->delete();
	
});