$ php artisan make:model Country -m
$ php artisan make:migration add_country_id_column_to_users –tables=users
migration file: add column country to the users
public function up()
{
Schema::table('users', function (Blueprint $table) {
//
$table->integer('country_id');
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::table('users', function (Blueprint $table) {
//
$table->dropColumn('country_id');
});
}
*_create_country_table.php
public function up()
{
Schema::create('countries', function (Blueprint $table) {
$table->increments('id');
$table->string('name');
$table->timestamps();
});
}
insert into countries (name) values (‘canada’);
insert into countries (name) values (‘india’);
insert into countries (name) values (‘german’);
update users set country_id=1 where id=1;
update users set country_id=3 where id=2;
class Country extends Model
{
//
public function posts(){
return $this->hasManyThrough('App\Post', 'App\User');
}
}
Route::get('/user/country', function(){
$country = Country::find(1);
foreach($country->posts as $post){
return $post->title;
}
});
一つhasManyで連結していれば、hasManyThroughで表示できる