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

Posted

技术标签:

【中文标题】如何在laravel中通过id选择不同表上的关系数据【英文标题】:How to select relational data on different table by id in laravel 【发布时间】:2019-08-18 19:12:50 【问题描述】:

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

*用户

标识 |姓名 |电子邮件 |密码 | created_at |更新时间

1 |约翰 |一个@邮箱 | ******* 等

*机器

标识 |名称机器 | created_at |更新时间

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

*维护

标识 |机器_id |用户 ID |问题 |状态 | created_at | 更新时间

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

现在我想在表“维护”上显示数据,显示数据“名称”(用户表)和 name_machine(机器表)按 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>

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

【问题讨论】:

【参考方案1】:

假设您的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>

【讨论】:

先生,您能告诉/解释一下为什么您在模型上使用 belongsTo 吗? 我使用 belongsTo 在你的表之间建立关系。看看你的桌子maintance。它有两个外键user_idmachine_id,foreign_key 使用belongsTo / belongsToMany 关系引用其父表。这里user 表和machine 表以id 作为主键并假设它是auto increment。显然maintance 表中的一个条目在其每个父表中都有一个条目。

以上是关于如何在laravel中通过id选择不同表上的关系数据的主要内容,如果未能解决你的问题,请参考以下文章

同一张表上的多个连接,在一个查询中计数

ActionScript3:在一个类中通过 addEventListener 读取文件,如何将数据传递给不同的类

如何在 Swift 中通过 MR 的 id 从 coredata 中选择一条记录

如何在SQLAlchemy模型的构造函数中通过关系存储数据?

多个表上的雄辩的自定义“属于”关系

如何关联数据库中通过 Rails 中的多对多关系连接的两个条目?