建立model文件,而且一塊兒建立migration文件:php
php artisan make:model Habit -m數據庫
建立多對多的中間表的方法:this
php artisan make:migration create_habit_user_table --create=habit_userspa
設計habit_user:設計
$table->unsignedInteger('user_id');code
$table->unsignedInteger('habit_id');對象
模型中定義多對多:同步
user模型:it
public function habits(){io
return $table->belongsToMany(Habit::class);
}
/*
belongsToMany參數說明:
第一個參數是 第二個Model
第二個參數是 關係表名
第三個參數是 第一個Model在關係表中的外鍵ID
第四個參數是 第二個Model在關係表中的外鍵ID
*/
Habit模型:
public function users(){
return $this->belongsToMany(User::class);
}
實現多對多關係:
第一種方法:attach(不會刪除以前的數據,只會把新添加的數據加上去)
//經過面向對象的方式綁定文章和標籤:
$label1=\App\Label::create(['name'=>'Python']);
$label2=\App\Label::create(['name'=>'Java']);
$article=\App\Article::first();
$article->labels()->attach([
$label1->id,
$label2->id
]);
dd($article->labels);
第二種方法:sync(使用sync會和數據庫同步,只會保留咱們填寫的id項,其餘的項都會刪除掉)
$label1=\App\Label::create(['name'=>'Python']);$label2=\App\Label::create(['name'=>'Java']);$article=\App\Article::first();$article->labels()->sync([ $label1->id, $label2->id]);dd($article->labels);解綁的方法使用detach,只須要傳入須要解綁的數據id就能夠了