zoukankan      html  css  js  c++  java
  • laravel模型关联

    hasOne        一对一     用户名-手机号
    hasMany         一对多       文章-评论
    belongTo       一对多反向   评论-文章
    belongsToMany      多对多     用户-角色
    hasManyThrough    远程一对多   国家-作者-文章
    moreghMany      多态关联    文章/视频-评论
    morephToMany    多态多对多   文章/视频-标签

    • 创建评论模型

    class Comment extends baseModel
    {
        public function post(){
            return $this->belongsTo('AppPost');
        }
    
        /**
         * notes: 评论所属用户
         * author: cible
         * time: 2018/12/4 上午8:44
         */
        public function user(){
            return $this->belongsTo('AppUser');
        }
    }
    • 增加评论

        public function comment(Post $post){
            $this->validate(request(),[
                'content'   => 'required|min:3'
            ]);
    
            $comment = new Comment();
            $comment->user_id   = Auth::id();
            $comment->content   = request('content');
            $post->comments()->save($comment);
    
            return back();
        }
    • 评论列表

    模型关联预加载(两种)  

    $books = AppBook::with('author')->get();
    $books->load('author','publisher');
    //实例
    $post->load('User');

    模版(直接在模版加载输出)

    @foreach($post->comments as $comments)
    <li class="list-group-item">
        <h5>{{$comments->created_at}} by {{$comments->user->name}}</h5>
        <div>
            {{$comments->content}}
        </div>
    </li>
    @endforeach
    • 获取评论总数

    模型关联计数

    $posts = AppPost::withCount('comments')->get();
    //实例
    $lists = Post::orderBy('created_at','desc')->withCount('Comments')->paginate(5);

    //视图层
    {{$list->comments_count}}
  • 相关阅读:
    git添加本地项目到git
    GitLab项目迁移到Gerrit
    flask一些资料
    openldap sshkey & 用户自定义属性
    openldap复制
    openldap主机访问控制(基于用户组)
    openldap主机访问控制(基于ip)
    openldap自定义schema
    openldap主机访问控制(基于hostname)
    openldap权限sudo
  • 原文地址:https://www.cnblogs.com/wanghaokun/p/10062191.html
Copyright © 2011-2022 走看看