php—从一个表中选择值,其中ID在laravel的另一个表中是json格式的

bxgwgixi  于 2021-06-20  发布在  Mysql
关注(0)|答案(1)|浏览(329)

我有一张table叫 journal_details 它有一列名为 transaction_by_to . 我在存钱 account_head_id 值为 json_encode 格式 transaction_by_to 在表中 journal_details . 现在我想运行一个select查询,从中获取帐户头名称 account_heads 哪里 transaction_by_to json格式的id将从 account_heads . 在控制器中,我尝试了类似于bellow的东西,但只得到一个。但我想展示一下 account_heads 对于所有json格式的ID。

  1. public function ledgerSubmit(Request $request)
  2. {
  3. $acId = $request->acount_head;
  4. $startDate = Carbon::parse($request->start_date)->format('Y-m-d');
  5. $endDate = Carbon::parse($request->end_date)->format('Y-m-d');
  6. $reportType = $request->report_type;
  7. $nameOfAccount = AccountHead::find($acId);
  8. $ledgers = DB::table('journal_details')
  9. ->join('journals', 'journal_details.journal_id', '=', 'journals.id')
  10. ->join('account_heads', 'journal_details.account_head_id', '=', 'account_heads.id')
  11. ->where('journal_details.account_head_id', $acId)
  12. ->select('journals.number as journalNo', 'journals.journal_date as journalDate', 'journal_details.*', 'account_heads.name as nameOfAccount')
  13. ->get();
  14. if (count($ledgers)) {
  15. $transactionByToId = $ledgers[0]->transaction_by_to;
  16. foreach (json_decode($transactionByToId) as $tId) {
  17. $transactionByTo = AccountHead::where('id', $tId)->get();
  18. }
  19. }
  20. return view('report.ledger.searched-result', compact('reportType', 'startDate', 'endDate', 'ledgers', 'transactionByTo', 'nameOfAccount'));
  21. }

在刀片视图中-

  1. @foreach($ledgers as $ledger)
  2. <tr>
  3. <td>{{ $loop->index + 1 }}</td>
  4. <td>{{ $ledger->journalNo }}</td>
  5. <td>{{ date('jS F, Y', strtotime($ledger->journalDate)) }}</td>
  6. <td>{{ $ledger->nameOfAccount }}</td>
  7. <td>
  8. {{ $transactionByTo[0]->name }}
  9. </td>
  10. <td>
  11. {{ number_format($ledger->debit, 2,".",",") }}
  12. </td>
  13. <td>
  14. {{ number_format($ledger->credit, 2,".",",") }}
  15. </td>
  16. </tr>
  17. @endforeach
  18. ``` `["16","17","7","11"]` 是 `transaction_by_to` json格式的列值 `journal_details` 这些身份证是 `id` 为了 `account_heads` table。
mwkjh3gx

mwkjh3gx1#

您的代码中有几个错误,如以下代码:

  1. foreach (json_decode($transactionByToId) as $tId) {
  2. $transactionByTo = AccountHead::where('id', $tId)->get();
  3. }

它将始终保持单个值,即最后一个值。所以看起来只有一个记录。
但是你为什么不一次做以下操作来获取所有记录:

  1. $accountHeadIds = json_decode($transactionByToId, true);
  2. $accountHeads = AccountHead::whereIn('id', $accountHeadIds)->get();

其次,我没有看到您正在处理accounthead变量(根据我的代码示例, $accountHeads )在不属于的视图文件中 $leders 变量。如果你想把它压下去的话 $ledgers 变量,然后你应该存储在它下面。
注意:我还没有测试上面的代码,但是概念是相似的。

相关问题