public function up()
{
Schema::create('posts', function (Blueprint $table) {
$table->increments('id');
$table->integer('user_id')->unsigned();
$table->string('title');
$table->text('content');
$table->timestamps();
});
}
$ php artisan migrate:refresh
Route::get('/basicinsert', function(){
$post = new Post();
$post->title = 'PHP post';
$post->user_id = 1;
$post->content = 'wow eloquent is really cool, look at this content';
$post->save();
});
mysql> select * from posts;
+—-+———+———-+—————————————————+———————+———————+———-+————+
| id | user_id | title | content | created_at | updated_at | is_admin | deleted_at |
+—-+———+———-+—————————————————+———————+———————+———-+————+
| 2 | 1 | PHP post | wow eloquent is really cool, look at this content | 2019-12-06 07:04:25 | 2019-12-06 07:04:25 | 0 | NULL |
+—-+———+———-+—————————————————+———————+———————+———-+————+
1 row in set (0.00 sec)
User.php
namespace App;
use Illuminate\Foundation\Auth\User as Authenticatable;
class User extends Authenticatable
{
/**
* The attributes that are mass assignable.
*
* @var array
*/
protected $fillable = [
'name', 'email', 'password',
];
/**
* The attributes that should be hidden for arrays.
*
* @var array
*/
protected $hidden = [
'password', 'remember_token',
];
public function post(){
return $this->hasOne('App\Post');
}
}
Route::get('/user/{id}/post', function($id){
return User::find(1)->post;
});
{“id”:2,”user_id”:1,”title”:”PHP post”,”content”:”wow eloquent is really cool, look at this content”,”created_at”:”2019-12-06 07:04:25″,”updated_at”:”2019-12-06 07:04:25″,”is_admin”:0,”deleted_at”:null}
userのモデル側にhasOneとしてるから、Post::find(4)->userだと表示されないのか??
あれ、これって、いわゆるエンティティリレーションモデルのこと??