刚刚开始学习 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
最佳答案
在您的用户模型中:
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/