建立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就能够了