您的位置:首页 > 编程语言 > PHP开发

laravel 多对多 belonsToMany

2015-09-14 23:38 696 查看
建库,建model

php artisan make:migration create_tags_table --create=tags
php artisan make:model Tag


加字段

<?php

use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class CreateTagsTable extends Migration
{

public function up()
{
Schema::create('tags', function (Blueprint $table) {
$table->increments('id');
$table->string('name');
$table->timestamps();
});
      //字母顺序,单数形式表名下划线结合定义中间表名
Schema::create('article_tag', function (Blueprint $table) {
$table->integer('tag_id')->unsigned()->index();
$table->foreign('tag_id')->references('id')->on('tags')->onDelete('cascade');
$table->integer('article_id')->unsigned()->index();
$table->foreign('article_id')->references('id')->on('articles')->onDelete('cascade');
$table->timestamps();
});
}

public function down()
{
Schema::drop('tags');
Schema::drop('article_tag');
}
}


添加关系

//在Article模型中
public function tags()
{
return $this->belongsToMany('App\Tag');
}
//在Tag中
public function articles()
{
return $this->belongsToMany('App\Article');
}


调用

$article->tags()->attach($id)
$tag->articles()->attach($id)


视图多选框

<div class='form-group'>
{!! Form::label('tags', 'Tags') !!}
{!! Form::select('tags[]',$tags, null, ['class'=>'form-control','multiple']) !!}
</div>


create , store

public function create()
{
$tags = \App\Tag::lists('name','id');

return view('articles.create', compact('tags'));
}

public function store(ArticleRequest $request)
{

$article = \Auth::user()->articles()->create($request->all());

$article->tags()->attach($request->tags);

flash()->success('Your article has been created!');

return  redirect('articles');

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: