我是 Laravel 的新手,不擅长语法。我想通过外键(该表的 ID)查看另一个表的值。
https://ibb.co/pXRFRHn https://ibb.co/pXRFRHn你可以在这张图片中看到我在用户和类别下获得了 id。我想要与这些 id 相关的标题。
我有表部分、用户和一个类。我用class_id
& user_id 作为节表中的外键。当我尝试显示数据时,我看到了 id,但我希望从该 id 中提取名称和其他字段。
控制器
public function index()
{
$sections = Section::all();
$classs = Classs::all();
$users = User::all();
return view('sections.index')->with('sections', $sections)->with('classs', $classs)->with('users', $users);
}
刀片/视图
<div class="box">
<div class="box-header">
<h3 class="box-title">All Sections</h3>
</div>
<div class="box-body">
<table class="table table-responsive">
<thead>
<tr>
<th>Name</th>
<th>Class</th>
<th>User</th>
<th>Modify</th>
</tr>
</thead>
<tbody>
@foreach($sections as $cat)
<tr>
<td>{{$cat->title}}</td>
<td>{{$cat->class_id}}</td>
<td>{{$cat->user_id}}</td>
<td>
<button class="btn btn-info" data-mytitle="{{$cat->title}}"
data-myclassid="{{$cat->class_id}}" data-myuserid="{{$cat->user_id}}"
data-catid={{$cat->id}} data-toggle="modal" data-target="#edit">Edit
</button>
<button class="btn btn-danger" data-catid={{$cat->id}} data-toggle="modal"
data-target="#delete">Delete
</button>
</td>
</tr>
@endforeach
</tbody>
</table>
</div>
</div>
具体来说...
<td>{{$cat->class_id}}</td>
由此,我得到了类 ID,但我也想要它的名称。
{{$cat->(class_id)->name}}"
然而,这并没有奏效。
我已经编辑了模型
class Classs extends Model
{
//
protected $fillable = [
'id',
'title',
];
public function section()
{
return $this->belongsTo('App\Section');
}
}
剖面模型
class Section extends Model
{
//
protected $fillable = [
'id',
'title',
'class_id',
'user_id',
];
public function classs()
{
return $this->hasMany('App\Classs');
}
}