代码之家  ›  专栏  ›  技术社区  ›  detinu20

通过外键显示数据

  •  3
  • detinu20  · 技术社区  · 7 年前

    我正试图通过关系和外键获取一些数据,但却把自己弄得一团糟。

    我有一个击球手谁用户可以评论,评论也可以由用户编辑,评论有自己的页面以及选择删除或编辑评论。这就是我的问题所在,我试图显示击球手的国籍,但只能检索他的国籍ID,而不能检索国家名称。

    这是我的桌子

    击球手 :ID,Name,bio,national\u ID, 国籍 :ID,国家/地区名称, 使用者 ID、名称、, 议论 :ID、注释、击球手ID、用户ID

    我的人际关系

    备注:

    public function batsmen(){
        return $this->belongsTo('App\Batsmen');
    }
    public function author()
    {
        return $this->belongsTo('App\User','user_id');
    }
    

       public function show($id)
        {
            $comment = Comment::find($id);
    
            return view('comments.show')->with('comment', $comment);
        }
    

    查看:

    <h4>{{$comment->batsmen->Nationality_id}}</h4>
    

    3 回复  |  直到 7 年前
        1
  •  0
  •   Sohel0415    7 年前

    制作另一个 relationship 方法 Batsman 模型类组件-

    public function nationality(){
         return $this->belongsTo('App\Nationality','Nationality_id');
    }
    

    然后在你看来-

    <h4>{{$comment->batsmen->nationality->country_name}}</h4>
    
        2
  •  0
  •   mputkowski Ilya Yaremchuk    7 年前

    试试这个

    public function show($id)
    {
       $comment = Comment::with('batsmen')->find($id);
    
       return view('comments.show')->with('comment', $comment);
    }
    
        3
  •  0
  •   Mahdi Younesi    7 年前

    您需要添加bastman和 国籍

    class Comment extends Model
    {
        public function nationality(){
    
           return $this->belongsTo('App\Nationality',Nationality_id,id);
       }
    }
    

    <h4>{{$comment->batsmen->Nationality->country_name}}</h4>