samedi 16 avril 2022

How to add a unique field in an existing database in laravel, using MongoDB?

     use App\Models\Product;

     $arr = [
         'id'    => 112,
         'name' => 'X1 SP',
         'slug' => 'x1_sp',
         'image' => [
               'imgAvata' => [
                     'url'   => 'abc.com'
                ],
                'imgProd' => [
                      'url'   => 'bcd.com'
                 ],
              ],
          ];
          // I handle :
          $product = Product::find($arr['id']);
          if (isset($arr['image']['imgFb'] && !empty($arr['image']['imgFb']))) {
              $arr['image']['imgFb'][0] = [
                    'url'   => 'aaa.com'
               ]
              $product->update($arr['image']['imgFb'][0]);
           } else {
               $arr['image']['imgFb'][] = [
                    'url'   => 'aaa.com'
                ]
               // way 1:
               $product->update($arr['image']['imgFb']); //Can't add mongoDB because it's empty, can't update
               // way 2:
               $product->create($arr['image']['imgFb']) // duplicate key error collection: product index: slug_1 dup key : { slug: null }
          }

I am checking if the data is already in the database.. If so, I update, if not, I proceed to add that field. But I only want to update a single field, not a lump of data.. When there is data in the database, I have successfully updated it. But when there is no such field in the database, I use the two methods above to fail. Please give me your opinion.

Database that I use : MongoDB + Laravel . Thanks



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire