Laravel vue array в проблеме с массивом

Я пытаюсь получить данные из двух таблиц базы данных и вернуть все в одном теле таблицы в моем компоненте.

Laravel vue array в проблеме с массивом

код

controller

public function show($id)
    {
        $history = Payment::where('account_id', $id)->with('account')->orderby('id', 'desc')->get();
        $balance = Account::where('id' , $id)->select('balance')->first();
        return response()->json([
            $history,$balance
        ]);
    }

component

<table class = "table table-bordered table-hover table-striped">
            <thead>
                <tr>
                    <th class = "text-center">#</th>
                    <th class = "text-center">Date</th>
                    <th class = "text-center">Amount</th>
                    <th class = "text-center">Note</th>
                </tr>
            </thead>
            <tbody>
                <tr v-for = "(history,index) in histories" @key = "index">
                    <td width = "50" class = "text-center">{{index+1}}</td>
                    <td class = "text-center" width = "100">
                        {{history.created_at}}
                    </td>
                    <td class = "text-center" width = "300">Rp. {{ formatPrice(history.balance) }}</td>
                    <td class = "text-center">{{history.note}}</td>
                </tr>
            </tbody>
</table>

export default {
        data() {
            return {
                histories : []
            }
        },
        beforeMount(){
            let user_id = this.user.id;
            axios.get('/api/account/'+user_id).then(response => this.histories = response.data)
        },
// rest of it
</script>

На изображении выше

Я получаю свой остаток средств из таблицы Account в массиве историй, а я получаю истории из таблицы Payment в массиве историй.

What I want is to take out histories array and join it under histories right where there balance data is. So later I can have something like:

histories: array[3]
0:...
1:...
2:...

Как я могу это сделать?

Обновлять

Я внес изменения в свой контроллер, и теперь результат данных стал таким, каким я хотел (все в одном массиве), но почему-то он не возвращает все данные.

код

public function show($id)
    {
        // $history = Payment::where('account_id', $id)->with('account')->orderby('id', 'desc')->get();
        // $balance = Account::where('id' , $id)->select('balance')->first();
        $history = DB::table('payments')
        ->where('account_id', $id)
        ->join('accounts', 'accounts.id', '=', 'payments.account_id')
        ->get();
        return response()->json($history, 200);
    }

Laravel vue array в проблеме с массивом

It supposed to be 3 but it only returns 2.

Структурированный массив Numpy
Структурированный массив Numpy
Однако в реальных проектах я чаще всего имею дело со списками, состоящими из нескольких типов данных. Как мы можем использовать массивы numpy, чтобы...
T - 1Bits: Генерация последовательного массива
T - 1Bits: Генерация последовательного массива
По мере того, как мы пишем все больше кода, мы привыкаем к определенным способам действий. То тут, то там мы находим код, который заставляет нас...
Что такое деструктуризация массива в JavaScript?
Что такое деструктуризация массива в JavaScript?
Деструктуризация позволяет распаковывать значения из массивов и добавлять их в отдельные переменные.
0
0
38
1
Перейти к ответу Данный вопрос помечен как решенный

Ответы 1

Ответ принят как подходящий

Решено

Я использовал метод push, и теперь он работает так, как я хотел. Вот последний код для тех, кто в этом нуждается.

public function show($id)
    {
        $his = Payment::where('account_id', $id)->with('account')->orderby('id', 'desc')->get();
        $balance = Account::where('id' , $id)->select('balance')->first();
        $history = $his->push($balance);
        return response()->json($history, 200);
    }

Надеюсь, это поможет.

Другие вопросы по теме