1、建表
2、创建模型
3、模型关联
class Article extends Model
{
protected $table = 'article';
public $timestamps = false;
/**
* 一对一
* // 1、创建文章表 article 和 作者表 author
* 文章表字段 主键id 文章内容 content 文章标题 title 作者主键id author_id
* 作者表字段 主键id 作者名称 auth_name
* @return \Illuminate\Database\Eloquent\Relations\HasOne
*/
public function author()
{
// $this->hasOne(Author::class,'本模型id','外键id(要关联表id)');
return $this->hasOne(Author::class,'id','auth_id');
}
/**
* 一对多
* // 创建文章评论表 comment
* 评论表字段 主键id 评论内容content 文章主键id article_id
* @return \Illuminate\Database\Eloquent\Relations\HasMany
*/
public function comment()
{
// $this->hasMany(Comment::class,'外键id(要关联表id)','本模型id');
return $this->hasMany(Comment::class,'article_id','id');
}
/**
* 多对多
* 创建关键词表 keyword 和 关系表 relation
* 关键词表字段 主键id 关键词 keyword
* 关系表字段 主键id 文章表主键 article_id 和 关键词表主键 keyword_id
* @return \Illuminate\Database\Eloquent\Relations\BelongsToMany
*/
public function keyword()
{
// $this->belongsToMany(Keyword::class,'关系表','关系表中本模型的id','关系表中的外键id(要关联表id)');
return $this->belongsToMany(Keyword::class,'relation','article_id','keyword_id');
}
}
class IndexController{
// 一对一
public function get_result()
{
Article::with('author:id')->select(['id','auth_id'])->get()->toArray();
//with里面对于author作者表而言,select对于article文章表
}
// 一对多
public function get_result()
{
Article::with('comment:id,content,article_id')->select(['id','name'])->get()->toArray();
}
// 多对多
public function get_result()
{
Article::with('keyword:keyword')->select(['name','id'])->get()->toArray();
}
}