Laravel API передает запрос на Vuejs, присоединяется к вложенной транзакции и заказывает Ttbles. - PullRequest
0 голосов
/ 21 октября 2018

Я создаю корзину для покупок, и у меня есть 3 таблицы, как вы можете видеть на картинке.во-первых, это продукты, заказы и последние транзакции, все заказанные продукты будут помещены в таблицу заказов вместе с идентификатором транзакции, кто бы ни принадлежал к этой транзакции, а таблица транзакций будет записывать общий баланс и изменения, и я хочу получить его вбазы данных с использованием построителя запросов laravel и конвертирования его в json, как на 2-м изображении ниже, я надеюсь, что мое объяснение не так запутанно.Заранее спасибо, ребята:)

enter image description here

Ответы [ 2 ]

0 голосов
/ 21 октября 2018

генерирующих моделей.

php artisan make:model Transaction
php artisan make:model Order
php artisan make:model Product

TransactionModel

public function orders()
{
    return $this->hasMany(Order::class, 'transaction_id', 'id');
}

ProductModel

public function orders()
{
    return $this->hasMany(Order:class, 'product_id', 'id');
}

OrderMode

public function product()
{
    return $this->belongsTo(Product::class, 'product_id', 'id');
}

public function transaction()
{
    return $this->belongsTo(Transaction::class, 'transaction_id', 'id');
}

Вы можете создать ResourceCollection для генерации желаемого вывода JSON.

php artisan make:resource TransactionCollection

, это создаст ResourceCollecion в app\Http\Resource\TransactionCollection

TransactionCollection

class TransactionCollection extends ResourceCollection
{
    /**
     * Transform the resource collection into an array.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return array
     */
    public function toArray($request)
    {
        $transactions = [];

        foreach($this->collection as $transaction) {

            $jsonTransaction = [
                'id'     => $transaction->id,
                'date'   => $transaction->transaction_date,
                'total'  => $transaction->transaction_total,
                'change' => $transaction->transaction_change,
                'orders' => []
            ];

            foreach($transaction->orders as $order) {

                $product = $order->product;

                array_push($jsonTransaction['orders'], [
                    'id'           => $order->id,
                    'product_name' => $product->product_name,
                    'category'     => $product->product_category,
                    'price'        => $order->order_price,
                    'quantity'     => $order->order_quantity
                ]);
            }

            array_push($transactions, $jsonTransaction);
        }
    }
}

TransactionController

public function getAllTransactions()
{
    // this will return your desired json result as you posted in the question.
    return TransactionCollection::make(Transaction::all());
}
0 голосов
/ 21 октября 2018

Выполните следующие действия:

1. Создание моделей и добавление отношений между ними.

Вы можете создавать модели для транзакции, заказа и продукта, используя phpartisan.

php artisan make:model Transaction
php artisan make:model Order
php artisan make:model Product

настроить их в соответствии с вашей структурой таблиц mysql.

Добавление связей.

Модель транзакции

public function order(){
  return $this->hasOne(Order::class, 'transaction_id', 'id');
}

ПорядокМодель

public function transaction(){
  return $this->belongsTo(Transaction::class);
}

public function products(){
  return $this->hasMany(Product::class, 'id', 'product_id');
}

Модель продукта

public function order(){
  return $this->belongsTo(Order::class);
}

2. Создание контроллера для обработки результатов.

Вы можете создать контроллер с помощью phpartisan.

php artisan make:controller TransactionController -r

Настройка нашего контроллера.

public function TransactionDetails($transactionID){

   $transaction = Transaction::where('id',$transactionID)->firstOrFail();
   $order = $transaction->order;
   $products = $order->products;

   $result = array();
   $result['transaction'] = $transaction;
   $result['transaction']['order'] = $order;
   $result['transaction']['order']['products'] = $products;

   return response()->json($result);

}

Это должно работать и дать вам желаемый результат, если возникнет какая-либо ошибка, дайте мне знать.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...