我有一个settings表格,其中包含所有可能的设置和每个设置的默认值。
我还有一个setting_user保存用户设置的表。这是用户和设置之间的数据透视表。
如果 UserA 中存在一行setting_user,则它将覆盖设置的默认值。
如果 UserA 中不存在任何行setting_user,则设置的值为默认值。
这是我的迁移:
Schema::create('settings', function (Blueprint $table) {
$table->uuid('id')->primary();
$table->text('description');
$table->string('key');
//$table->json('default_value')->nullable();
$table->text('default_value')->nullable();
$table->timestamps();
});
Schema::create('setting_user', function (Blueprint $table) {
$table->uuid('id')->primary();
$table->uuid('user_id')->index();
$table->uuid('setting_id')->index();
$table->text('setting_value')->nullable();
$table->timestamps();
});
我想settings为 UserA 返回表中所有行的集合,并在setting_user.
换句话说,如果settings表中有 50 行,我想返回 50 个项目,无论 UserA 是否有每个 in 的匹配/数据透视条目setting_user。
用例如下:用户可以有自定义设置(自定义设置的值保存setting_user在列中setting_value)。如果他们从未设置自定义设置,则透视行不存在,因此我们将设置值视为表中的default_value列settings。
我从这样的事情开始,在\App\User:
$defaultAndUserSettings = \App\Setting::query()
->join('setting_user', 'settings.id', '=', 'setting_user.setting_id', 'left outer')
->where('setting_user.user_id', $this->id)
//-> plus also all other Setting rows where the user has no pivot for
->get();
但我找不到让它工作的方法。以上将仅返回存在枢轴的设置。