1 常见的数据库表关系
One-To-One //一对一
One-To-Many //一对多
Many-To-Many //多对多
在刚刚开始接触到这些概念的时候,其实我是不太理解的。但是一旦你将这些概念应用到生活中,理解起来就很简单了,就举一个与我们在网上经常见到的例子:
User-To-Profile // One-To-One
User-To-Articles // One-To-Many
Articles-To-Tags // Many-To-Many
翻译过来就是:
- 一个用户对应一个用户档案
- 一个用户可以发表多篇文章
- 文章和标签确实多对多的关系,一篇文章可以有多个标签;一个标签可以属于多篇文章
在这些关系模型中,最难实现的就是Many-To-Many这种多对多的关系,不过借助Laravel的强大的Eloquent,实现这个功能还是比较顺心的。
2 创建数据库表
创建Question.php数据库模型时,同时也创建一个Questions迁移文件
php artisan make:model Question -m
Quesrtions.php
2017_02_02_072801_create_questions_table.php
创建questions表
Schema::create('Questions', function (Blueprint $table) {
$table->increments('id');
$table->string('title');
$table->text('content');
$table->timestamps();
});
创建Topic.php数据库模型,同时也创建一个Topics数据库迁移文件
php artisan make:model Topic -m
Topics.php
2017_02_02_072801_create_Topics_table.php
创建topics表
Schema::create('tags', function (Blueprint $table) {
$table->increments('id');
$table->string('name');
$table->timestamps();
});
当然,解决这个经典问题单单靠这两张表还不足够,需要在这两张表之外再建立一个关系表,用来将article和tag联系起来,在Laravel中,如果你遵循官方的标准规则,第三张表应该是这样的:
创建 question_topic迁移文件
php artisan make:migration create_articles_tags_table --create=question_topic
生成一个迁移文件
2017_06_08_235159_create_questions_topics_table.php
创建question_topic
Schema::create('question_topic', function (Blueprint $table) {
$table->increments('id');
$table->integer('question_id')->unsigned()->index();
$table->integer('topic_id')->unsigned()->index();
$table->timestamps();
});
如果你没有按照官方的规范来,你需要在模型中指定外键。
3. 创建模型并指定关系
在Topic.php中:
class Topic extends Model
{
protected $fillable = ['name','questions_count'];
public function questions()
{
//这里的数据库模型为Question数据模型
return $this->belongsToMany(Question::class)->withTimestamps()
}
在Question.php中:
class Question extends Model
{
protected $fillable = ['title','body', 'user_id'];
public function topics()
{
//这里的数据库模型为Topic数据模型
return $this->belongsToMany(Topic::class)->withTimestamps()
}
这里注意两点:
你可以在声明关系的时候指定外键,如
$this->belongsToMany(Topic::class,'foreign_key', 'other_key');
或者传递第二个数据库表的表名作为第二个参数(your_table_name)
return $this->belongsToMany(Topic::class,'your_table_name')->withTimestamps()
如果在article_tag表中你添加了timestamps(),即表中出现created_at和updated_at这两个字段,在Article中声明关系的时候需要这样:
return $this->belongsToMany(Topic::class)->withTimestamps();
4 在Controller中使用
如果我们想查看某个提问含有哪些话题,我们可以这样:
$question= Question::find($id);
dd($question->topic);
如果我们想通过某个话题下面有多少个提问:
public function showArticleByTagName($name)
{
$topic= Topic::where('value','=',$name)->first();
dd($topic->questions);
}
以上,就实现了在Laravel中的Many-To-Many