如何查询数据库以获取产品订单到用户配置文件

问题描述 投票:2回答:3

刚开始学习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

php laravel
3个回答
1
投票

在您的用户模型中:

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);
}

在你的控制器中

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

1
投票

您的查询看起来不对。您正在使用latest()返回表中的最新订单,但之后使用get。如果你想要的话我会先使用最后一个订单()

 $orders=Order::where('user_id',$user->id)->latest()->first();

我想虽然你不想要一行,但是所有的行,在这种情况下删除latest()

$orders=Order::where('user_id',$user->id)->get();

然后可能使用orderBy('created_at')或类似的东西来获得最新的第一个。


0
投票

试试这段代码:

$data = ['user' => $user, 'orders' => $orders];
return view('profile.index', $data);
© www.soinside.com 2019 - 2024. All rights reserved.