dellamina's avatar

How to have only one active item in a oneToMany realtion

I'm currently working on an application where the Project model has a File field and I would like to let the user upload new revisions and also rollback to previously uploaded files. My idea was to use a oneToMany relationship between my 2 models to allow the user to upload multiple files and add an additional field to my Project model to point to the currently active file but I'm not so sure how to implement this.

0 likes
2 replies
frankincredible's avatar
Level 14

So the way you described is certainly one possibility.

To create a one to many relationship, you'd add a project_id column to your files table:

Schema::table('files', function (Blueprint $table) {
    $table->unsignedBigInteger('project_id');

    $table->foreign('project_id')->references('id')->on('projects');
});

To make your naming less confusing, you might want to consider renaming the file_id column on your projects table to active_file_id.

From there, your Project model would need two relationships:

public function activeFile()
{
    return $this->hasOne(File::class, 'id', 'active_file_id');
}

public function files()
{
    return $this->hasMany(File::class);
}

Having an active_file_id column on the projects table would ensure there is only ever one active file for a project.

That said, you may alternatively consider adding an is_active boolean field to the files table instead. That would allow you to have multiple active files, if you choose, but you'd have to be more protective through checks if you wanted to make sure there is only ever one active file.

1 like
dellamina's avatar

Thanks, that is exactly was I was looking for.

Please or to participate in this conversation.