我刚刚开始学习 Laravel 4,遇到了一个小问题,我很好奇是否有解决方案。我有一个多语言食谱数据库,简而言之,我的数据库建模如下:
Schema::create('language', function(Blueprint $table) {
$table->string('id', 2)->primary();
$table->string('display_name');
$table->timestamps();
});
Schema::create('recipe', function(Blueprint $table) {
$table->increments('id');
$table->string('name');
$table->string('slug')->unique();
$table->timestamps();
});
Schema::create('translated_recipe', function(Blueprint $table) {
$table->increments('id');
$table->integer('recipe_id')->unsigned();
$table->foreign('recipe_id')->references('id')->on('recipe')->onDelete('cascade');
$table->string('language_id', 2);
$table->foreign('language_id')->references('id')->on('language');
$table->string('translated_name')
$table->timestamps();
});
我的模型如下所示:
class Language extends Eloquent {
protected $table = 'language';
public function translatedRecipes() {
return $this->hasMany('TranslatedRecipe');
}
}
class Recipe extends Eloquent {
protected $table = 'recipe';
public function translations() {
return $this->hasMany('TranslatedRecipe');
}
}
class TranslatedRecipe extends Eloquent {
protected $table = 'translated_recipe';
public function recipe() {
return $this->belongsTo('Recipe');
}
}
然后我有一些基本的播种:
Language::create(array('id' => 'en', 'display_name' => 'English'));
Recipe::create(array('name' => 'First Recipe', 'slug' => 'first_recipe'));
棘手的部分来了。如何使用 Eloquent 插入翻译后的食谱?我已经走到了这一步:
$recipe = Recipe::all()->first();
$lang = Language::all()->first();
$translatedRecipe = new TranslatedRecipe;
$translatedRecipe->translated_name = $lang->display_name.' '.$recipe->name;
我可以使用查询生成器轻松地进行 INSERT:
DB::table('translated_recipe')->insert(
array(
'recipe_id' => $recipe->id,
'language_id' => $lang->id,
'translated_name' => $translatedRecipe->translated_name
)
);
它没有设置时间戳,因为我猜这是 Eloquent 的一个特性。有没有办法让它 100% 雄辩?我不能这样做:
$translatedRecipe = $recipe->translations()->save($translatedRecipe);
...因为 SQL 由于缺少第二个外键而引发“完整性约束违规:1452 ...”错误。