$ php artisan make:model Post -m
Schema::create('posts', function (Blueprint $table) {
$table->increments('id');
$table->integer('user_id')->unsigned()->nullable()->index();
$table->string('title');
$table->text('body');
$table->timestamps();
});
$ php artisan migrate
User.php
public function posts(){
return $this->hasMany('App\Post');
}
Post.php
protected $fillable = [
'title',
'body'
];
$ php artisan tinker
Psy Shell v0.7.2 (PHP 7.1.7 — cli) by Justin Hileman
>>> App\User::create([‘name’=>’Peter’, ’email’=>’peter@gmail.com’, ‘password’=>’1234’]);
=> App\User {#634
name: “Peter”,
email: “peter@gmail.com”,
updated_at: “2019-12-08 18:25:17”,
created_at: “2019-12-08 18:25:17”,
id: 1,
}
Route::get('/create', function(){
$user = User::findOrFail(1);
$post = new Post(['title'=>'My first post', 'body'=>'I love laravel']);
$user->posts()->save($post);
});
read
Route::get('/read', function(){
$user = User::findOrFail(1);
return $user->posts;
});
Route::get('/read', function(){
$user = User::findOrFail(1);
foreach($user->posts as $post){
echo $post->title . "<br>";
}
});
update
Route::get('/update', function(){
$user = User::find(1);
$user->posts()->whereId(1)->update(['title'=>'I love', 'body'=>'this is awsome, thank you']);
});
Route::get('/delete', function(){
$user = User::find(1);
$user->posts()->whereId(1)->delete();
});
insertはsave(), updateはupdate(), deleteはdelete()メソッドです。
大分つかめてきました。
keep going