我在Laravel中定义了3个表,如下所示:
Schema::create('locales', function (Blueprint $table) {
$table->string('id', 2);
$table->string('name', 5000);
$table->timestamps();
$table->primary('id');
});
Schema::create('i18n_keys', function (Blueprint $table) {
$table->string('id', 255);
$table->timestamps();
$table->primary('id');
});
Schema::create('i18ns', function (Blueprint $table) {
$table->bigIncrements('id');
$table->string('key', 255);
$table->string('locale', 2);
$table->string('translation', 5000)->nullable();
$table->timestamps();
$table->foreign('key')->references('id')->on('i18n_keys')->onDelete('cascade')->onUpdate('cascade');
$table->foreign('locale')->references('id')->on('locales')->onDelete('cascade')->onUpdate('cascade');
$table->unique(array('key', 'locale'));
});
现在的问题是如何在Laravel中以编程方式实现以下
SELECT
语句。我的意思是不直接运行SQL语句。SELECT `il`.`key`, `il`.`locale`, `in`.`translation` FROM
(SELECT `ik`.`id` AS `key`, `lo`.`id` AS `locale` FROM `i18n_keys` as `ik` CROSS JOIN `locales` as `lo`) AS `il`
left join `i18ns` as `in`
ON `in`.`key` = `il`.`key`
and `in`.`locale` = `il`.`locale`;
目的是提取还没有翻译的键。但是我喜欢用查询生成器或雄辩的或类似的方法而不是直接传递查询。有什么办法吗?
最佳答案
您可以尝试以下代码:
use App\Models\I18nKey;
$ik = I18nKey::crossJoin('locales as lo')
->select('i18n_keys.id AS key', 'lo.id AS locale');
$res = \DB::table(\DB::raw("({$ik->toSql()}) AS il"))
->mergeBindings($ik->getQuery())
->leftjoin('i18ns as in',function($join){
$join->on('in.key', '=', 'il.key')
->whereColumn('in.locale', 'il.locale');
})->select('il.key','il.locale','in.translation')->get();