如何从laravel中的外键中提取数据?

How to extract data from foreign keys in laravel?

我是 Laravel 的新手,不擅长语法。我想通过外键(那个 table 的 id)查看另一个 table 的值。

https://ibb.co/pXRFRHn 您可以在这张图片中看到我在用户 & class 下获取 ID。我想要与这些 ID 关联的标题。

我有 table 个部分、用户和一个 class。我使用 class_id & user_id 作为 table 部分的外键。当我尝试显示数据时,我看到了 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);
}

Blade/View

<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>

由此,我得到了 class 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');
}}

而不是

{{$cat->(class_id)->name}}

尝试

{{$cat->classs->name}}

您正在使用 $cat->(class_id) 访问 table 部分中的外键,这有效。但是现在您想通过其动态属性查询关系,这需要 $cat->classs->"any properties of classs".

尝试$section->classs,它应该是一个数组,因为关系是 hasMany,也许你应该创建一个过滤器来获得正确的 id。

Eloquent 有另一种方法可以与 SQL where 子句和其他子句建立关系。

$section->classs()->where('title', 'foo')->first();


小技巧,如果你想试试。

返回视图时,可以用Laravel中的->with()方法,使用简洁的php函数,调用和代码清晰。


return view('sections.index')->with(compact('sections', 'classs', 'users'));

这对我有用...有点长但很简单

{{ \Illuminate\Support\Facades\DB::table('class')->where('id',$cat->class_id)->value('name')}}