【问题标题】:How to select relational data on different table by id in laravel如何在laravel中通过id选择不同表上的关系数据
【发布时间】: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>

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

【问题讨论】:

    标签: laravel model controller relation


    【解决方案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 表中的一个条目在其每个父表中都有一个条目。
    猜你喜欢
    • 1970-01-01
    • 2019-04-17
    • 1970-01-01
    • 2015-06-02
    • 1970-01-01
    • 1970-01-01
    • 2018-10-04
    • 1970-01-01
    • 2017-01-24
    相关资源
    最近更新 更多