常见的对应关系模式
在实际的开发中,我们经常会接触到几种常见的对应关系模式:
1 2 3 | One-To-One //一对一 One-To-Many //一对多 Many-To-Many //多对多 |
在刚刚开始接触到这些概念的时候,其实我是不太理解的。但是一旦你将这些概念应用到生活中,理解起来就很简单了,就举一个与我们在网上经常见到的例子:
1 2 3 | User-To-Profile // One-To-One User-To-Articles // One-To-Many Articles-To-Tags // Many-To-Many |
翻译过来就是:
- 一个用户对应一个用户档案
- 一个用户可以发表多篇文章
- 而文章和标签确实多对多的关系,一篇文章可以有多个标签;一个标签可以属于多篇文章
在这些关系模型中,最难实现的就是Many-To-Many
这种多对多的关系,不过借助Laravel的强大的Eloquent
,实现这个功能还是比较顺心的。
1. 创建数据库表
创建articles
表
1 2 3 4 5 6 | Schema::create( 'articles' , function (Blueprint $table ) { $table ->increments( 'id' ); $table ->string( 'title' ); $table ->text( 'content' ); $table ->timestamps(); }); |
创建tags
表
1 2 3 4 5 | Schema::create( 'tags' , function (Blueprint $table ) { $table ->increments( 'id' ); $table ->string( 'name' ); $table ->timestamps(); }); |
当然,解决这个经典问题单单靠这两张表还不足够,需要在这两张表之外再建立一个关系表,用来将article
和tag
联系起来,在Laravel中,如果你遵循官方的标准规则,第三张表应该是这样的:
表名 article_tag
1 2 3 4 5 6 | Schema::create( 'article_tag' , function (Blueprint $table ) { $table ->integer( 'article_id' )->unsigned()->index(); $table ->foreign( 'article_id' )->references( 'id' )->on( 'articles' )->onDelete( 'cascade' ); $table ->integer( 'tag_id' )->unsigned()->index(); $table ->foreign( 'tag_id' )->references( 'id' )->on( 'tags' )->onDelete( 'cascade' ); }); |
如果你没有按照官方的规范来,你需要在模型中指定外键。
2. 创建模型并指定关系
在Article.php
中:
1 2 3 4 | public function tags() { return $this ->belongsToMany( 'AppTag' ); } |
在Tag.php
中:
1 2 3 4 | public function articles() { return $this ->belongsToMany( 'AppArticle' ); } |
这里注意两点:
- 你可以在声明关系的时候指定外键,如
$this->belongsToMany('AppArticle','foreign_key', 'other_key');
- 如果在article_tag表中你添加了timestamps(),即表中出现created_at和updated_at这两个字段,在Article中声明关系的时候需要这样:
return $this->belongsToMany('AppTag')->withTimestamps();
3. 在Controller中使用
如果我们想查看某个文章含有哪些标签,我们可以这样:
1 2 | $article = Article::find( $id ); dd( $article ->tags); |
如果我们想通过某个标签来查找文章:
1 2 3 4 5 | public function showArticleByTagName( $name ) { $tag = Tag::where( 'value' , '=' , $name )->first(); dd( $tag ->articles); } |
以上,就实现了在Laravel中的Many-To-Many
,更多关于Laravel 多对多关系模式的资料请关注IT俱乐部其它相关文章!