在laravel的另一个表中,从ID为json格式的表中选择值

时间:2018-07-31 18:09:59

标签: php mysql arrays json laravel

我有一个名为journal_details的表,并且有一个名为transaction_by_to的列。我将account_head_id的值以json_encode的格式保存在表transaction_by_to中的journal_details中。现在,我要运行一个选择查询,以从account_heads获取帐户名称,其中JSON格式的transaction_by_to ID将在account_heads中找到ID。在控制器中,我尝试了类似波纹管的方法,但是只有一种。但我想显示account_heads中所有JSON格式ID的全部信息。

public function ledgerSubmit(Request $request)
{
    $acId       = $request->acount_head;
    $startDate  = Carbon::parse($request->start_date)->format('Y-m-d');
    $endDate    = Carbon::parse($request->end_date)->format('Y-m-d');
    $reportType = $request->report_type;

    $nameOfAccount = AccountHead::find($acId);
            $ledgers = DB::table('journal_details')
                    ->join('journals', 'journal_details.journal_id', '=', 'journals.id')
                    ->join('account_heads', 'journal_details.account_head_id', '=', 'account_heads.id')
                    ->where('journal_details.account_head_id', $acId)
                    ->select('journals.number as journalNo', 'journals.journal_date as journalDate', 'journal_details.*', 'account_heads.name as nameOfAccount')
                    ->get();

    if (count($ledgers)) {
            $transactionByToId = $ledgers[0]->transaction_by_to;

            foreach (json_decode($transactionByToId) as $tId) {
                $transactionByTo = AccountHead::where('id', $tId)->get();
            }
    }
return view('report.ledger.searched-result', compact('reportType', 'startDate', 'endDate', 'ledgers', 'transactionByTo', 'nameOfAccount'));
}

在刀片视图中-

@foreach($ledgers as $ledger)
        <tr>
            <td>{{ $loop->index + 1 }}</td>
            <td>{{ $ledger->journalNo }}</td>
            <td>{{ date('jS F, Y', strtotime($ledger->journalDate)) }}</td>
            <td>{{ $ledger->nameOfAccount }}</td>
            <td>
                {{ $transactionByTo[0]->name }}
            </td>
            <td>
                {{ number_format($ledger->debit, 2,".",",") }}
            </td>
            <td>
                {{ number_format($ledger->credit, 2,".",",") }}
            </td>
        </tr>
@endforeach

["16","17","7","11"]transaction_by_to中json格式的journal_details列值,id表的这些ID是account_heads

1 个答案:

答案 0 :(得分:1)

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

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

它将始终保留单个值,即最后一个值。因此,似乎只有一条记录。

但是您为什么不执行以下操作一次获取所有记录:

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

第二,我看不到您正在视图文件中处理Account Head变量(根据我的代码示例,$accountHeads),该变量不是$leders变量的一部分。如果要在$ledgers变量下包含该变量,则应将其存储在该变量下。

注意:我没有测试上面的代码,但是概念很相似。