如何在laravel中通过id选择不同表上的关系数据

问题描述 投票:0回答:1

我有3个表,名称是:用户,机器,维护。像这样的架构

*用户

id |名字|电子邮件|密码| created_at |的updated_at

1 |约翰|一个@ mail | *******等

*机

id | name_machine | created_at |的updated_at

1 |震惊| .....等等

*保养

id | Machine_id | user_id |问题|状态| created_at |的updated_at

1 | ......... 1 ........ | ....... 1 ...... |等等等等

现在我想在表“维护”上显示数据,显示数据“名称”(用户表)和名称机器(机器表)按ID。

这是我的控制者和我的观点

 public function show($id)
{
    $maintance = Maintance::all();
    return view('users.view',['maintance' => $maintance]);
}

我的看法

<table class="table table-hover">
              <tbody><tr>
                <th>Machine</th>
                <th>Question</th>
                <th>User Input</th>
                <th>Action</th>
                <th>Tanggal</th>
              </tr>
              @foreach ($maintance as $i)
              <tr>
                <td>{{ $i->machine_id}} </td>// i want to show name machine here
                <td>{{ $i->Question}}</td>
                <td>{{ $i->user_id}}</td> // name users to 
                <td><span class="label label-primary">Lihat Data</span></td>
                <td>{{ $i->created_at}}</td>
              </tr>
              @endforeach
            </tbody></table>

此视图数据没有错误,但我不知道如何从不同的表中显示此数据。有人可以帮忙吗?

laravel model controller relation
1个回答
0
投票

假设你的Maintance模型低于,

public function user(){
  return $this->belongsTo(User::class);
}
public function machine(){
  return $this->belongsTo(Machine::class);
}

假设您的模型具有以上关系。

并执行以下操作以获取您的数据,

$maintance = Maintance::with(['user','machine'])->get();

并在你看来

<table class="table table-hover">
          <tbody><tr>
            <th>Machine</th>
            <th>Question</th>
            <th>User Input</th>
            <th>Action</th>
            <th>Tanggal</th>
          </tr>
          @foreach ($maintance as $i)
          <tr>
            <td>{{ $i->machine->machine_name}} </td>// i want to show name machine here
            <td>{{ $i->Question}}</td>
            <td>{{ $i->user->name}}</td> // name users to 
            <td><span class="label label-primary">Lihat Data</span></td>
            <td>{{ $i->created_at}}</td>
          </tr>
          @endforeach
        </tbody></table>
© www.soinside.com 2019 - 2024. All rights reserved.