php - 如何查询数据库以将产品订单抓取到用户个人资料中

标签 php laravel

刚刚开始学习 laravel/PHP,我在查询用户个人资料页面上的用户订单时遇到了一些麻烦。因此,在用户购买产品后,我希望订单显示在用户个人页面上。正确的做法是什么。那么我如何正确查询数据库,以便在用户个人资料页面上显示刚刚购买的商品的产品名称、数量和总数。

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\User;
use App\Order;

class UserProfileController extends Controller
{
    public function index(User $user)
    {
      $orders=Order::where('user_id',$user->id)->latest()->get();
      return view('profile.index', compact('user','orders'));
    }

}

不确定这是否正确


@extends('layouts.app')

@section('content')
<div class="row">
  <div class="container">
  <h2> {{$user->name}}</h2>

  @forelse($orders as $order)
    <h4>{{$order->total}}</h4>


    @empty

    <h5>No items</h5>


    @endforelse
  </div>



</div>




@endsection

enter image description here

最佳答案

在您的用户模型中:

public function orders(){
    return $this->hasMany(Order::class)->latest();
}

在您的订单模型中

//For the listing of product in an order
public function products(){
    return $this->belongsToMany(Product::class);
}

在你的 Controller 中

public function index(User $user)
    {
      $user->load('orders.products');
      return view('profile.index', compact('user'));
    }

在你看来

@forelse($user->orders as $order)

    <h4>{{$order->total}}</h4>
          @forelse($order->products as $product)
              {{ $product->name }}
          @empty
              no product
          @endforelse


    @empty

    <h5>No items</h5>


@endforelse

关于php - 如何查询数据库以将产品订单抓取到用户个人资料中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47775728/

相关文章:

javascript - 如何使用php中的while循环和javascript来显示从数据库获取的多个图像中的特定点击图像?

php - PHP中的动态行列显示

php - 将程序代码转换为 Blob 的类

php - Eloquent 查询 1 :n relationship

laravel - 模型的正常方法被属性错误

JavaScript 确认取消在 Laravel 表单上不起作用

php - Redhat php-apd安装

php - 网站关闭优惠 PHP/Javascript

php - laravel 中的增量列

php - Laravel:从包扩展 subview 中的布局