【问题标题】:How to display category name from different table instead of category id如何显示来自不同表的类别名称而不是类别 ID
【发布时间】:2019-06-28 22:23:32
【问题描述】:

我有 2 张桌子 - 一张 with forum category name field called "disp_name" and "ID" called "forum_cat" 和其他with forum posts id, forum post content and cat_id and more called "forum"

我有模型“Forum_cats”

    <?php

    namespace App;

    use Illuminate\Database\Eloquent\Model;

    class Forum_cats extends Model
    {

    protected $table = 'forum_cat';

    public $timestamps = false;

    }

和模型“论坛”

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Forum extends Model
{   

protected $table = 'forum';

public $timestamps = false;

}

控制器:

public function index(){


    $forum = Forum::orderBy('timestamp', 'desc')->paginate(20);

//next variable is for different place
    $news = Neww::orderBy('date', 'DESC')->paginate(20);


    return view ('lapas.pamata.index',[
        'news'=>$news,
        'forum'=> $forum,
    ]);
}

刀片:

@foreach($forum as $forums)
          <li>
            <div class="media">
              <div class="media-body"> <a href="#" class="catg_title"> 
              {{$forums->title}}</a> </div>
              <i class="far fa-comment-alt"></i>&nbsp;{{$forums->comments}} 
              Kategorija:{{$forums->cat_id}}
            </div>
          </li>
        @endforeach

所以现在的视图是like this where after "Kategorija" i have only category id

如何从表“forum_cat”中生成名称“Kategorija”输出字段“disp_name”。

有人可以说有很多关于我的问题的帖子,但我整天都在努力解决这个问题。 我知道它与 hasOne、belongsTo 和 hasMany 有关,但我不明白如何在我的代码中纠正它们。

【问题讨论】:

  • 你能试着简化一下吗?你想展示什么? (哪个表的哪个字段)

标签: php laravel-5


【解决方案1】:

所以,我假设(但仍然不确定)该论坛属于一个类别。

您的论坛模型应该是:

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Forum extends Model {   

    protected $table = 'forum';
    public $timestamps = false;

    public category(){
            return $this->belongsTo('App\Forum_cats', 'cat_id', 'id');
    }
}

你的刀片应该是:

@foreach($forum as $forums)
          <li>
            <div class="media">
              <div class="media-body"> <a href="#" class="catg_title"> 
              {{$forums->title}}</a> </div>
              <i class="far fa-comment-alt"></i>&nbsp;{{$forums->comments}} 
              Kategorija:{{$forums->category->disp_name}}
            </div>
          </li>
@endforeach

这对你有用吗? 您也可以考虑预先加载:

https://laravel.com/docs/5.8/eloquent-relationships#constraining-eager-loads

【讨论】:

    猜你喜欢
    • 2015-02-16
    • 1970-01-01
    • 2012-09-18
    • 2020-09-15
    • 2011-09-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-03-05
    相关资源
    最近更新 更多