我有2张桌子-1张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> {{$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,但是我不明白我们在我的代码中如何对它们进行纠正。
答案 0 :(得分:0)
因此,我假设(但仍不确定)该论坛属于某个类别。
您的论坛模型应为:
<?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> {{$forums->comments}}
Kategorija:{{$forums->category->disp_name}}
</div>
</li>
@endforeach
这对您有用吗? 您还可以考虑增加负载:
https://laravel.com/docs/5.8/eloquent-relationships#constraining-eager-loads