【发布时间】:2019-08-28 10:53:49
【问题描述】:
我是 Laravel 的新手,语法不好。我想通过外键(该表的id)查看另一个表的值。
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>
具体...
<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');
}}
【问题讨论】:
-
$section->class() 或 $class->section()
-
当然忘记 IE 或 Edge ;)
-
你在问什么请解释一下。
-
这也是我的问题,你可以检查一下,我没有得到正确的答案。
-
@AbdulRehman 如果你不喜欢你在另一个问题上得到的答案,你不应该接受。
标签: php laravel eloquent foreign-keys relational-database