Skip to content

How to replicate WITH hasMany() relationship and unique() attribute #48

@mahmoudmohamedramadan

Description

@mahmoudmohamedramadan

Welcome,

I have installed this awesome package, then I used Cloneable trait in User model. I have Post model also and every user hasMany posts and every post belongsTo one user WITH a unique title....as my code show

....

class Post extends Model
{
    use Cloneable;

    protected $fillable = [
        'title',
        'body',
        'user_id',
    ];

    public function user()
    {
        return $this->belongsTo(User::class, 'user_id', 'id');
    }

    public function onCloning($src, $child = null)
    {
        $faker = Faker::create($this);

        $src['title'] = $faker->unique()->name;
    }
}
...

class User extends Authenticatable
{
    ....
    use Cloneable;

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'name', 'email', 'password',
    ];

    ...

    protected $cloneable_relations = ['posts'];

    public function posts()
    {
        return $this->hasMany(Post::class, 'user_id', 'id');
    }
}

When I try to clone the post, this operation is successful, BUT when I try to clone the user this ERROR SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry 'testing' for key 'posts_title_unique' (SQL: insert into 'posts' ('title', 'body', 'user_id', 'updated_at', 'created_at') values (testing, wesdfdsfffsdf, 54, 2021-07-14 15:00:54, 2021-07-14 15:00:54)) triggered

I know that the solution is to try to change the title while cloning, BUT I do NOT know how can I do it (I have tried onCloning() method BUT WITHOUT avail)

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