如何解决如何将数据库表中的一个“id”匹配到另一个 - Laravel
我是 Laravel 的新手,我无法将一个数据库表中的“id”匹配到另一个。
在我看来,我正在显示一个表格,其中包含从我的数据库中提取的数据。表的一列是从“索赔”表中提取的“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>
解决方法
如果需要基于父表获取数据,请尝试使用 Laravel 关系。
根据您的表格设计,您需要选择关系。
所以你的代码看起来像这样,
$account = Account::with('relationShipName')->orderBy('account_name')->get();
在 Account
模型中
public function relationShipName() {
return $this->hasOne('AnotherModel:class');
}
如果您按照 laravel 标准设计了表结构,那么它会起作用,否则您需要传递 local
和 foreign
键。
欲知更多: Laravel Relationships
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。