定义 laravel 关系时找不到列 1054 错误

Column not found 1054 error when defining laravel relationship

我有两个 table:订单和 Order_details。这两个table之间是一对多的关系。

订单字段是:

Order_details 字段:

order_id 是一个外键,在订单 table

上引用 id_order

订购型号

 //
protected $primaryKey = 'id_order';
protected $fillable = [
    'invoice', 'customer_id', 'user_id', 'total'
];

public function order_detail()
{
    return $this->hasMany(Order_detail::class);
}

Order_detail 型号

protected $primaryKey = 'order_detail_id';

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

protected $guarded = [];

public function order()
{
    return $this->belongsTo(Order::class, 'order_id', 'order_detail_id');
}

当我尝试向这些 table 中插入数据时,出现错误

SQLSTATE[42S22]: Column not found: 1054 Unknown column 'order_id_order' in 'field list' (SQL: insert into `order_details` (`product_id`, `qty`, `order_id_order`, `updated_at`, `created_at`) values (8, 1, 10, 2020-09-07 10:30:04, 2020-09-07 10:30:04))

为什么 laravel 假设我有 order_id_order 字段而不是 order_id?以及如何修复它?

谢谢

这里,在你的问题中,orders table 是父 table,order_details 是子 table。所以一个订单可以有很多订单明细。所以有one-to-many关系

Order.php即订单模型中,您需要具有前向关系,并与主键和外键进行适当的映射。

public function orderDetails()
{
    #1st arg is related model,
    #2nd arg is related column of order_details table
    #3rd arg is related column of orders table
    return $this->hasMany(OrderDetail::class, 'order_id', 'order_id');
}

现在进入 OrderDetail.php 即 order_detail 模型,您需要具有如下所示的反比关系。

public function order()
{
    #1st arg is related model,
    #2nd arg is related column of orders table
    #3rd arg is related column of order_details table
    return $this->belongsTo(Order::class, 'order_id', 'order_id');
}

在两个函数上定义外键

订购型号

public function order()
{
    return $this->belongsTo(Order::class, 'order_id');
}

订单详情模型

public function order_detail()
{
    return $this->hasMany(Order_detail::class,'order_id');
}