Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Open
mahmoudmohamedramadan opened this issue Jul 14, 2021 · 1 comment

Comments

@mahmoudmohamedramadan
Copy link

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)

@waiaryi
Copy link

waiaryi commented Feb 2, 2022

Hi, just change $src['title'] by $this->title on onCloning method.

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;
        $this->title = $faker->unique()->name;
    }
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants