首页 > 解决方案 > 如何使用laravel在数据库表的单行中以数组格式存储表表

问题描述

在下表中,我一直使用数据以数组格式存储,该数组格式应存储在数据库表的单行中。

 <table class="table">
        <tr>
            <th>transaction_number</th>
            <th>date</th>
            <th>item_number</th>
            <th>desc</th>
            <th>variant_code</th>
            <th>quantity</th>
            <th>cost</th>
        </tr>
        @php ($current_transaction_number = null)

        @foreach ($items as $item)
            @if ($loop->index > 0 && $current_transaction_number != $item->transaction_number)
               @include ('subtotal', compact('items', 'current_transaction_number'))
            @endif
            <tr>
                @if ($current_transaction_number == $item->transaction_number)
                    <td colspan="2"></td>
                @else
                    @php ($current_transaction_number = $item->transaction_number)
                    <td>{{ $item->transaction_number }}</td>
                    <td>{{ $item->date }}</td>
                @endif
                <td>{{ $item->item_number }}</td>
                <td>{{ $item->desc }}</td>
                <td>{{ $item->variant_code }}</td>
                <td>{{ $item->quantity }}</td>
                <td>{{ $item->cost }}</td>
            </tr>


@if ($loop->last)
               @include ('subtotal', compact('items', 'current_transaction_number'))
               @include ('total', compact('items'))
            @endif
        @endforeach
    </table>

标签: arrayslaravel

解决方案


我不确定我是否完全理解了这个问题,也看不出将所有数据存储在一列中的原因,但您绝对可以使用MySQL JSON field.

在您的迁移中使用$table->json('name_of_the_column')->nullable();创建此列。

在您的模型中添加:

protected $casts = [
     'name_of_the_column' => 'array'
];

然后你将能够检索像Model::where('name_of_the_column->name_of_the_property', 'Key')->get();

更多详情可以看这个链接:https ://www.qcode.in/use-mysql-json-field-in-laravel/

我希望这有帮助。


推荐阅读