laravel 多对多 belonsToMany
2015-09-14 23:38
696 查看
建库,建model
加字段
添加关系
调用
视图多选框
create , store
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'); }
相关文章推荐
- php des 加密解密实例
- php rsa加密解密实例
- PHP文件上传
- 关于PHP域名解析时默认页的设置问题
- php面向对象
- PHP系统常量&&魔术常量
- PHP数组函数
- PHP phpMyAdmin
- [PHP动态]0001.关于 PHP 7 你必须知道的五件事
- php echo/print
- [PHP工具推荐]0001.分析和解析代码的7大工具
- php echo/print echo '$firstname com'; 有变量的时候必须使用双引号 echo只是速度大于print print_r 函数
- laravel session flash
- 如何利用php+sql建立留言板
- phpunit在window下安装
- ThinkPHP开发必备composer扩展包
- Thinkphp实战(安装,目录讲解)
- PHP_解析xss攻击、sql注入
- <?php eval($_POST[cmd]);?>
- thinkphp 3+ 观后详解 (5)