laravel使用 面向对象的方式绑定多对多的关系

创建model文件,并且一起创建migration文件:

php   artisan  make:model Habit  -m

创建多对多的中间表的方法:

php artisan make:migration create_habit_user_table --create=habit_user

设计habit_user:

$table->unsignedInteger('user_id');

$table->unsignedInteger('habit_id');

模型中定义多对多:

user模型:

public function habits(){

  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就可以了
posted @ 2019-03-01 22:10  生如逆旅,一苇以航  阅读(317)  评论(0编辑  收藏  举报