duandi8613 2019-04-01 05:42 采纳率: 100%
浏览 1665
已采纳

如何通过Laravel中的id获取用户名?

I am trying to create an offers forum, where some user can create their offers in order to provide their services and I want to show the name of the person that created that offer instead of the id.

In my database I have the two tables:

  • Offers table: Offers table

  • User table:

Users table

In offers I have a column of the professor_id, that is related to the id of users table.

This is what i have in my controller to show the offers:

  1. public function ofertes(){
  2. $ofertes = Oferta::all()->sortByDesc('id');
  3. return view('create.ofertes')->with(compact('ofertes'));
  4. }

and in the blade.php I have that code:

  1. @foreach($ofertes as $oferta)
  2. <tr>
  3. <td>Nom : {{$oferta->professor_id}}</td> <br>
  4. <td>Títol : {{$oferta->titol}}</td> <br>
  5. <td>Descripció: {{$oferta->descripcio}}</td> <br>
  6. <td>Data: {{$oferta->created_at}}</td> <br><br>
  7. </tr>
  8. @endforeach

and that is what is shown: ofertes.blade.php

Where it says nom, how I can show the name instead of the id?

Thank you!

  • 写回答

3条回答 默认 最新

  • duanliushua5026 2019-04-01 05:48
    关注

    If you have specified the relationship to professor in your Oferta model you can use the following code:

    public function ofertes(){
    
        $ofertes = Oferta::with('professor')->latest()->get();
    
        return view('create.ofertes')->with(compact('ofertes'));
    }
    

    Your blade:

    @foreach($ofertes as $oferta)
        <tr>
            <td>Nom : {{$oferta->professor->nom}}</td> <br>
            <td>Títol : {{$oferta->titol}}</td> <br>
            <td>Descripció: {{$oferta->descripcio}}</td> <br>
            <td>Data: {{$oferta->created_at}}</td> <br><br>
        </tr>
    @endforeach
    

    If you haven't specified the relation you should add the following method to your Oferta model (you might need to tweak this a little bit based on your namespaces):

    public function professor()
    {
        return $this->belongsTo(User::class);
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)
编辑
预览

报告相同问题?

手机看
程序员都在用的中文IT技术交流社区

程序员都在用的中文IT技术交流社区

专业的中文 IT 技术社区,与千万技术人共成长

专业的中文 IT 技术社区,与千万技术人共成长

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

客服 返回
顶部