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
Advertisement
Answer
Here, in your question, orders
table is the parent table and order_details
is the child table. So one order can have many order details. So there is one-to-many
relationship.
In Order.php
i.e order model, you need to have forward relation, with proper mapping with the primary key and foreign key.
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'); }
Now coming to OrderDetail.php
i.e. order_detail model, you need to have inverse relation as given below.
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'); }