To ensure that a user can only have one vote per opportunity, you can use a unique constraint on the combination of user_id and opportunity_id instead of making them a composite primary key. This approach simplifies the database schema and avoids the issues you're encountering with foreign key constraints.
Here's how you can achieve this in your migration file:
- Create the Votes Table with a Unique Constraint:
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CreateVotesTable extends Migration
{
public function up()
{
Schema::create('votes', function (Blueprint $table) {
$table->id();
$table->unsignedBigInteger('user_id');
$table->unsignedBigInteger('opportunity_id');
$table->integer('score'); // Assuming you have a score field
$table->timestamps();
// Add foreign key constraints
$table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
$table->foreign('opportunity_id')->references('id')->on('opportunities')->onDelete('cascade');
// Add unique constraint on user_id and opportunity_id
$table->unique(['user_id', 'opportunity_id']);
});
}
public function down()
{
Schema::dropIfExists('votes');
}
}
- Update or Create Vote:
You can use the updateOrCreate method in your model to ensure that a vote is either updated or created if it doesn't exist:
use App\Models\Vote;
public function castVote($userId, $opportunityId, $score)
{
Vote::updateOrCreate(
['user_id' => $userId, 'opportunity_id' => $opportunityId],
['score' => $score]
);
}
- Handling Foreign Key in Comments Table:
If you have a comments table that references the votes table, ensure that the vote_id column is properly set up as a foreign key:
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CreateCommentsTable extends Migration
{
public function up()
{
Schema::create('comments', function (Blueprint $table) {
$table->id();
$table->unsignedBigInteger('vote_id');
$table->text('comment');
$table->timestamps();
// Add foreign key constraint
$table->foreign('vote_id')->references('id')->on('votes')->onDelete('cascade');
});
}
public function down()
{
Schema::dropIfExists('comments');
}
}
By using a unique constraint on the combination of user_id and opportunity_id, you ensure that each user can only vote once per opportunity. This approach avoids the complexity of composite primary keys and makes it easier to manage foreign key relationships.