I have in my project laravel 7.x issue eloquent one to many relationship my model sallat is :
public function sallproducts()
{
return $this->hasMany(sallat_product::class);
}
and the sallat_products model is:
public function sallats()
{
return $this->belongsTo(sallat::class);
}
and my input method in controller is:
$sallats = new sallat();
$sallats->full_total = $request->full_total;
$sallats->save();
$sall = new sallat_product();
$sall->name_product = $request->name_product;
$sall->total = $request->total;
$sall->quantity = $request->quantity;
$sall->price = $request->price;
$sall->sale = $request->sale;
$sallats->sallproducts()->save($sall);
return "done";
or I can do this:
$sallats->sallproducts()->save($sall);
return "done";
then I tried to test the post request on postman
{
"full_total":87997,
"arr":
[
{
"name_product":"سيتامول",
"quantity":222,
"total":299,
"price":100,
"sale":"10+2"
}
]
}
I want to insert multi records in one request in this way above, and i have this error on postman :
SQLSTATE[42S22]: Column not found: 1054 Unknown column 'sallat_id' in 'field list' (SQL: insert into
sallat_products
(name_product
,total
,quantity
,price
,sale
,sallat_id
,updated_at
,created_at
) values (?, ?, ?, ?, ?, 18, 2021-07-11 02:51:59, 2021-07-11 02:51:59))
this is sallat_products migration :
$table->id();
$table->bigInteger('id_sallat')->unsigned();
$table->foreign('id_sallat')->references('id')->on('sallats');
$table->string('name_product');
$table->integer('total');
$table->integer('quantity');
$table->integer('price');
$table->string('sale');
$table->timestamps();
and sallats migration:
$table->id();
$table->integer('full_total');
$table->timestamps();
so what should i do can anyone help me please to solute this problem.
In your sallat_products
migration it should be:
$table->bigInteger('sallat_id')->unsigned();
$table->foreign('sallat_id')->references('id')->on('sallats');
instead of id_sallat
to match Laravel conventions.
Alternatively, you can specify the name of this column as the second arguments to hasMany
and belongsTo
in your relationships.