【问题标题】:How to get the ID from this function and match it to my other table to get the Product_name (laravel)如何从此函数获取 ID 并将其与我的其他表匹配以获取 Product_name (laravel)
【发布时间】:2019-06-23 06:55:12
【问题描述】:
public function viewCustomerOrders(){
    $orders = Order::with('ordersz')->get();

    return view('admin.orders.view_customers_order')->with(compact('orders'));
}

我的公共函数代码

<?php
    namespace App;

    use Illuminate\Database\Eloquent\Model;

    class Order extends Model
    {
        public function ordersz(){
            return $this->hasMany('App\OrderProduct','order_id');
        }
        function product() {
            return $this->hasOne('App\Product');
        }
    }

我与我的订单模型的关系

这个可以吗?

foreach($orders->ordersz as $try){
    $getTheProductIDfromOrdersTabel= $try->product_id;
    matchItTomyProductTableTogetName= Product::where('id',$getTheProductIDfromOrdersTabel)->get();
}

因为我有 orders 表和 order_products 表,里面有 order_id 和 product_id,我想从我的条件中获取 product_id 并将其匹配到我的 products 表中以显示它们的 product_names。

【问题讨论】:

  • 请教我如何调用我的视图文件

标签: laravel


【解决方案1】:

您所描述的是many-to-many 关系。为了包含所有必要的数据,您将使用eager loading

考虑三个表 - ordersproductsorder_product。各个模型的定义如下:

订购

class Order extends Model
{
    public function products()
    {
        return $this->belongsToMany(Product::class);
    }
}

产品

class Product extends Model
{
    public function orders()
    {
        return $this->belongsToMany(Order::class);
    }
}

数据透视表 - order_product - 只需要两列:order_idproduct_id

现在您的控制器方法可以更新为:

public function viewCustomerOrders()
{
    return view('admin.orders.view_customers_order')->with([
        'orders' => Order::with('products')->get()
    ]);
}

最后,要在视图文件中显示信息,请使用@foreach

@foreach($orders as $order)
    Order ID: {{ $order->id }}
    @foreach($order->products as $product)
        Product Name: {{ $product->name }}
    @endforeach
@endforeach

【讨论】:

  • SQLSTATE[42S02]:未找到基表或视图:1146 表 'e_grocery.order_product' 不存在(SQL:选择 products.*、order_product.order_id as @ 987654337@, order_product.product_id as pivot_product_id from products 内连接 order_product on products.id = order_product.product_id in product_id @986547.@986547.@ , 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20)))
  • 先生,它现在可以工作了,我制作了一个新的 order_product 表,但是请先生,再提供一个帮助,你能解释一下这个代码是如何工作的吗,非常感谢,
猜你喜欢
  • 2022-01-25
  • 2020-02-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-06-01
  • 2015-07-29
相关资源
最近更新 更多