I have two tables: Order and Order_details. Between these two tables, there is a one-to-many relationship.
Order fields are:
id_order
invoice
customer_id
user_id
total
Order_details fields:
- order_detail_id
- order_id
- product_id
- qty
- price
order_id is a foreign key which references to id_order on orders table
Order Model
//
protected $primaryKey = 'id_order';
protected $fillable = [
'invoice', 'customer_id', 'user_id', 'total'
];
public function order_detail()
{
return $this->hasMany(Order_detail::class);
}
Order_detail model
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');
}
When i tried to insert data to these table, i got an error
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))
Why laravel assume i have order_id_order field instead of order_id? And how to fix it?
Thank you
Order
andOrder_Detail
both models code are same. In both model,$primaryKey
is sameorder_detail_id
. And another thing, put your controller code too, from where the data is being inserted. - GhanuBha$fillable
and$guarded
at the same time. Use one OR the other. - Qirelid
. If you follow the Laravel naming convention with table-names and primary-keys, you do not have to specify any arguments tobelongsTo()
other than the related model-class. It will save you a lot of headache, I can nearly guarantee it. - Qirelforeign_key
andloca_key
then laravel auto detect and postfix_id
onprimaryKey
. So, here, inOrder
model, you have to pass other 2 argumets that you have passed inbelongsTo
relationship. Add this'order_id', 'order_detail_id'
inHasMany
relationship and try. - GhanuBha