Yes, you can use polymorphism to achieve this. In Laravel, you can use the morphTo and morphMany relationships to create a polymorphic relationship between the Translate model and the Text and Sentence models.
First, you need to modify the translations table to include the polymorphic columns. You can do this by adding translatable_type and translatable_id columns to the table:
Schema::create('translations', function (Blueprint $table) {
$table->id();
$table->unsignedBigInteger('source_id');
$table->unsignedBigInteger('target_id');
$table->unsignedBigInteger('author_id')->nullable();
$table->unsignedBigInteger('translatable_id');
$table->string('translatable_type');
$table->timestamps();
$table->foreign('source_id')->references('id')->on('sentences');
$table->foreign('target_id')->references('id')->on('sentences');
$table->foreign('author_id')->references('id')->on('people');
$table->unique(['source_id', 'target_id']);
});
Next, you need to update the Translate model to define the polymorphic relationship:
use Illuminate\Database\Eloquent\Model;
class Translate extends Model
{
public function translatable()
{
return $this->morphTo();
}
}
Then, update the Text and Sentence models to define the inverse of the polymorphic relationship:
use Illuminate\Database\Eloquent\Model;
class Text extends Model
{
public function translations()
{
return $this->morphMany(Translate::class, 'translatable');
}
}
class Sentence extends Model
{
public function translations()
{
return $this->morphMany(Translate::class, 'translatable');
}
}
Now, you can use the polymorphic relationship to retrieve translations for both Text and Sentence models. For example, to get all translations for a specific Text model:
$text = Text::find(1);
$translations = $text->translations;
To create a translation for a Text or Sentence model, you can use the create method on the translations relationship:
$text = Text::find(1);
$translation = $text->translations()->create([
'source_id' => 1,
'target_id' => 2,
'author_id' => 1,
]);
Remember to adjust the column names and relationships according to your specific application.