在 Eloquent 中获取多个关系

Getting multiple relationships in Eloquent

Fundamental misunderstanding of model in Eloquent (Outside of Laravel)

我之前的问题是 ceejayoz 帮助我指出了正确的方向,但这让我想到了一个基本上是新问题的问题。

我正在开发一个简单的化学品跟踪数据库,并使用化学品 table 构建它来跟踪大部分信息,但我有一些字段最初是枚举,但我意识到这不会为。。。工作。公司、房间和位置现在有单独的 table。所有这些额外的 table 仅包含一个 ID 和字段,因此公司是:

1 | 'FISHER'

2 | 'BDH'

等等

我能做到

$company = chemical::find(4)->company;

例如,这将为我提供该化学品的公司名称,但我想要做的是显示一个 table,其中包含每种化学品的所有信息,以及相关的公司名称、房间、位置。 我只是不确定如何做到这一点。

我怎样才能找到所有化学品的关联公司?

$chemicals = company::all()->company;

不起作用,我知道为什么了。

$chemicals = chemical::all();   

foreach($chemicals as $chem) {
    echo $chem->company . "<br />";
}  

会帮我找到关联公司,这很好,但是就综合性而言,我从那里去哪里?table?

这个问题有点不清楚,但是对于包含其公司数据的 table 化学品,您会按照这些思路做一些事情。在您的控制器中:

// we use with() to "eager load" the company data
// this makes the following line execute two queries
// without the with(), our Blade template will make a query
// to the companies table for EVERY row in the table

// if you have hundreds/thousands of chemicals, you'll
// want to consider paginate() instead of get() too

$chemicals = Chemical::with('company')->get();

return view('your.view')->withChemicals($chemicals);

在您的 Blade 视图中,您可以访问每个化学品公司的所有属性:

<table>
  @foreach($chemicals as $chemical)
    <tr>
      <td>{{ $chemical->name }}</td>
      <td>{{ $chemical->company->name }}</td>
    </tr>
  @endforeach
</table>

您没有指定表 companyroomlocationchemicals 的关联方式。但是,如果都是belongsTo类型的关系,那我相信你要找的是Eager Loading:

Eloquent can "eager load" relationships at the time you query the parent model. Eager loading alleviates the N + 1 query problem.

要预先加载多个关系,您可以执行以下操作:

$chemicals = chemical::with('company', 'room', 'location')->get();

如果您使用的是像 Twig 或 Blade 这样的模板引擎(希望您是),那么您可以将 $chemicals 直接传递给模板。否则,您可以按照问题中的说明遍历 $chemicals

echo "<table><thead><tr>
      <th>Chemical ID</th>
      <th>Chemical Name</th>
      <th>Company Name</th>
      <th>Location Name</th>
      <th>Room Name</th>
      </tr></thead><tbody>";

foreach($chemicals as $chem) {
    echo "<tr><td>{$chem->id}</td>
              <td>{$chem->name}</td>
              <td>{$chem->company->name}</td>
              <td>{$chem->location->name}</td>
              <td>{$chem->room->name}</td>
          </tr>";
}
echo "</tbody></table>";

另请注意,Eloquent 中的惯例是将您的模型 class 名称大写(Chemicals,而不是 chemicals)。

我猜,你问的是这个:

chemicals: id, company (ENUM), ...

现在您将数据提取到

companies: id, name (same as ENUM in chemicals previously)

如果是这样,那么您可以做两件事:

  1. idcompany_id 建立普通关系成为关键 更新您的 chemicals table 根据 company enum/string 值添加适当的 company_id 值,然后删除 company 列。它可能需要更多的调整,例如。在你打电话给 chemical->company 获取公司名称的任何地方(变成 chemical->company->name

  2. 根据 chemicals.companycompanies.name 字段创建关系。

当然第一个选项比较长运行。