In my project, I use Laravel 8 with Mongodb as my database, and jenssegers/laravel-mongodb as its driver.
Let say I have a collection named products which has relationship embedsOne to vendors.
when I create a new product, how can I insert existing vendor to this new product? I tried the following
$vendor = Vendor::find($request->vendor);
$product = Product::create([
'name'=>$request->name
'vendor'=>$vendor
]);
which resulting the following document.
{
"_id": "606ffac287be2020b968c613",
"name": "product name",
"vendor": {
"incrementing": true,
"exists": true,
"wasRecentlyCreated": false,
"timestamps": true
},
"updated_at": "2021-04-09T06:57:06.032000Z",
"created_at": "2021-04-09T06:57:06.032000Z"
}
I also tried to insert the vendor just like in the documentation said:
$vendor = Vendor::find($request->vendor);
$product = Product::create([
'name'=>$request->name
]);
$product->vendor()->save($vendor);
but that way the vendor does not saved at all. so, what is the correct way to insert existing vendor to product?