laravel 模型关联 一对一,一对多,多对多

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();
    }
}

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值