Skip to content

Double query when using $with in model, and SerializesModels trait #55546

Closed
@alexmontoanelli

Description

@alexmontoanelli

Laravel Version

12.x

PHP Version

8.3

Database Driver & Version

No response

Description

If you have a model, with the 'public $with' attribute to autoEagerLoad relationships,
when, unserializing a model in (queue worker, after a job pickup), the Model itself load the relationship ($with attribute), and if the relationship was loaded before the job dispatched, the Trait SerializesAndRestoresModelIdentifiers will load that relationship again.

In my investigations, the SerializesAndRestoresModelIdentifiers::110, is the issue where
he tries to load the relation.

If he use loadMissing, the behavior is OK, no relation already loaded will be loaded.

Steps To Reproduce

class User extends Model {

  public $with = 'country';

  public function country() : HasOne {
    return $this->hasOne(Country::class);
 }

}

class Country extends Model {
}


//load the user
$user = User::find(1);

//$user now has country RelationShip autoloaded loaded


//dispatch a job
$job = new SomeJob($user);

//the model will be serialized
dispatch($job);


//when job is picked up by a worker
//the model with be loaded again from database,
//the $with  will be loaded by the model itset
//the Trait, will reload the relation again (SerializesAndRestoresModelIdentifiers line 110)

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions