【问题标题】:How can I match one 'id' from a database table to another - Laravel如何将数据库表中的一个“id”匹配到另一个 - Laravel
【发布时间】:2021-01-26 11:13:24
【问题描述】:

我是 Laravel 的新手,我在将一个数据库表中的“id”匹配到另一个时遇到了麻烦。

在我看来,我正在显示一个表格,其中包含从我的数据库中获取的数据。该表的一列是从“claims”表中提取的“id”。

我还有一个“accounts”表,用于存储相关“id”的“account_name”。所以我试图在与'id'匹配的地方显示'account_name'。

控制器中的代码

$account = Account::orderBy('account_name')->get();

$data = [
'claim_data' => $claim_data,
'client' => $client,
'start_date' => $start_date,
'end_date' => $end_date,
'capacity' => $capacity,
'status' => $status,
'account' => $account
];

$returnHTML = view('reports._get_client_claim_report')->with($data)->render();

查看代码

<td>{{ ($claim->client_account_id == $account->id ? $account->account_name : '') }}</td>

【问题讨论】:

  • 欢迎来到SO ...您遇到了什么问题?
  • 请将您的两张表的结构添加到您的帖子中,以便更好地理解并更好地帮助您。

标签: database laravel eloquent relational-database one-to-one


【解决方案1】:

如果需要根据父表获取数据,请尝试使用laravel关系。

根据您的表格设计,您需要选择关系。

所以你的代码会是这样的,

$account = Account::with('relationShipName')->orderBy('account_name')->get();

Account 模型中

public function relationShipName() {
      return $this->hasOne('AnotherModel:class');
}

如果你按照 laravel 标准设计了你的表结构,那么它会起作用,否则你需要传递你的 localforeign 密钥。

更多: Laravel Relationships

【讨论】:

    猜你喜欢
    • 2015-10-27
    • 1970-01-01
    • 1970-01-01
    • 2010-09-18
    • 2017-03-15
    • 2018-08-30
    • 2021-10-31
    • 1970-01-01
    相关资源
    最近更新 更多