您好,我有一个名为order_product的表,我想从其中获取值,该表的模型名为order_product With Values:

public $timestamps = false;

    protected $fillable = [
        'order_id',
        'product_id',
        'amount',
    ];

这是型号Order的代码:

public $timestamps = true;

    protected $fillable = [
        'order_number',
        'client_id',
        'description',
    ];


    public function client()
    {
        return $this->belongsTo(Client::class);
    }

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

    public function orders()
    {
        return $this->belongsToMany(order_product::class);
    }

一个专业的人帮助我,向我解释了关系是如何工作的,所以clientproducts工作得很好,但orders在SQL中会出错.

这是我在控制器中执行的代码:

$orders = Order::where('id', $id)->firstOrFail();
$orders->load('client', 'products','orders');

我得到的错误是:

SQLSTATE[42S02]: Base table or view not found: 1146 Table 'user_project_db.order_products' doesn't exist

文件order_product的名称应该是什么,这样查询才能正确执行?

推荐答案

在阅读了下面您的答案后,我更改了我的答案.

您的餐桌关系是orders-order_product-products.

https://webdevetc.com/blog/laravel-naming-conventions/
Pivot tables岁以下

您命名数据透视表的方式已经正确.

order_product是以多对多的方式将orders连接到products.

因此,我认为您可以try 执行以下操作.

在产品内部模型中添加此关系.

public function orders() 
{
   return $this->belongsToMany(Order::class, 'order_product');
}

并按型号顺序添加另一个连接

public function products() 
{
   return $this->belongsToMany(Product::class, 'order_product');
}

belongsToMany接受2个参数,第一个是模型目标,第二个是表轴名称,在本例中为order_product.

在这种情况下,额外的型号OrderProduct是可选的.

要将产品添加到订单中,您可以使用Attach

 $order = Order::find($order_id);
 $order->products()->attach($product_id);

或者如果透视表中有额外的字段

// first implement this change inside Order model

return $this->belongsToMany(Product::class, 'order_product')
   ->withPivot('price', 'qty');

// to attach for example price and qty
$order->products()->attach($product_id, ['price' => 200', 'qty'=> 1]);

查询价格的步骤

$order_product = $order->products()
   ->where('product_id', $product_id)
   ->first()->pivot;
$price = $order_product->price;
$qty = $order_product->qty;

回到你自己的问题上.

不需要在订单模型中添加Orders().

And load only the first 2 relationship should be enough.
$order->load('clients', 'products');

Laravel相关问答推荐

发送邮箱后,Laravel重定向偶尔会导致错误500

密码确认在Livewire中不匹配

如何在 Laravel 中使用 return 停止 Trait php 的执行

Laravel Eloquent查询与集合优化

验证判断请求的值是否存在于另一个表 Laravel 9 中

如何传递多个参数给路由

导出所有客户端不起作用,文件保存时没有名称和扩展名

API GET 请求得到与数据库记录不同的结果

Laravel + Plupload 上传到 S3 响应以进行预检无效 - CORS

Laravel Auth::attempt() 返回 false

Laravel Session 总是改变 Laravel 5.4 中的每个刷新/请求

在 Laravel 5 中扩展请求类

Laravel - 超过 PHP 最大上传大小限制时验证文件大小

如何利用 StorageFacade 的 Filesystem 类的 glob 方法?

Web 服务器如何处理请求?

验证匹配字符串

在 Laravel 应用程序中在哪里指定应用程序版本?

Laravel 错误声明 App\Exceptions\Handler::report(Throwable $exception)

无法打开laravel.log:无法打开流

在 Laravel 5.4 中将文件存储在公共目录和存储中的区别