Update of embedded model does not affect in related collection

327 Views Asked by At

What I get:

My controller creates one intance of Message in the message collection. It contains an embedded instance of Image. It also creates a duplicate of the embedded Image in the images collection.

After updating the name property of Image the update affects only the embedded instance, but not the related duplicate in the images collection.

What I want:

I want a real belonging of the duplicate in the images collection to the embedded Image. I don't want to have update the related Image manually.

Is that possible by using jenssegers/laravel-mongodb?

My model:

namespace App\Models;

use Jenssegers\Mongodb\Eloquent\Model;
use Jenssegers\Mongodb\Relations\EmbedsMany;

class Message extends Model
{
    public function images(): EmbedsMany
    {
        return $this->embedsMany(Image::class);
    }

My controller method:

public function create(Request $request)
{
    $message = Message::create($request->all());

    $imageController = new ImageController();
    $image = $message->images()->associate(
        /* ImageController->create() simply creates an Image object
           without touching the database */
        $imageController->create($request->input('image'))
    );
    $message->save();

    $foo = $message->images()->first();
    $foo->name = 'bar';
    $foo->save();

    return response()->json($message, 201);
}
0

There are 0 best solutions below