Laravel 5.4 Database Structure

Relationships

 

f:id:monteecristoo:20170513231001p:plain

model A: User

protected $fillable = [ DBのカラム]

 public function messages) {

    return $this->hasMany(Message::class);

model B: Message

protected $fillable = [ DBのカラム] foreign_key は登録しなくてOK

public function users() {
   return $this->belongsTo(User::class);

}

DB_B 側に foreign_keyを設定(この場合user_id)

 

tinkerの操作

userを作成した状態で...

$user=App\User::find(1)->messages()->create(['message'=>'test from tinker'])

=> App\Message {#703
message: "test from tinker",
user_id: 1,
updated_at: "2017-05-13 13:35:31",
created_at: "2017-05-13 13:35:31",
id: 1,
}

 

*messagesのカラムにid, timestamps, foreign_key以外設定しなかった場合

= protected $fillable を設定していない場合

$user=App\User::find(1)->messages()->create()

ERROR

$user=App\User::find(1)->messages()->create([])

=> App\Message {#678
user_id: 1,
updated_at: "2017-05-13 20:22:52",
created_at: "2017-05-13 20:22:52",
id: 1,
}

f:id:monteecristoo:20170513224408p:plain

Max section4 lecture21

model A: Post

public function categories() {
    return $this->belongsToMany(Category::class)

}

model B: Category

public function posts() {
    return $this->belongsToMany(Post::class)

}

table: A table: B ともにforeign_keyなし

  • create intermediate table

php artisan make:migration create_category_post_table --create="category_post"

intermediate table 内に foreign_keyを作る

$table=>integer('category_id');

$table=>integer('post_id');

category, post tableの各々にデータを作成

  • category, post の各関係をcategory_postにデータ作成

それぞれのORMインスタンスを生成後attach()

$post = App\Post::find(5)

$category = App\Category::find(8)

$post->categories()->attach($category)

特定の$postを特定の$categoryにattach

tinker上で

$post=App\Post::find(1)->categories()

=> Illuminate\Database\Eloquent\Collection {#710
all: [
App\Category {#708
id: 1,
created_at: null,
updated_at: null,
pivot: Illuminate\Database\Eloquent\Relations\Pivot {#693
post_id: 1,
category_id: 1,
},
},
],
}
>>> $user=App\User::find(2)->categories
=> Illuminate\Database\Eloquent\Collection {#715
all: [
App\Category {#719
id: 3,
created_at: null,
updated_at: null,
pivot: Illuminate\Database\Eloquent\Relations\Pivot {#707
post_id: 2,
category_id: 3,
},
},
App\Category {#716
id: 2,
created_at: null,
updated_at: null,
pivot: Illuminate\Database\Eloquent\Relations\Pivot {#678
post_id: 2,
category_id: 2,
},
},
],
}

$post=App\Post::find(2)->caetegories()->orderBy('id')->get()

 

f:id:monteecristoo:20170513225021p:plain

 

f:id:monteecristoo:20170513225421p:plain

 

 

f:id:monteecristoo:20170513225615p:plain