Jav*_*ozo 8 php relationship laravel
我想创建一个一对一的多态关系允许空关系。
例子:
Schema::create('ps_assistances', function (Blueprint $table) {
$table->bigIncrements('id');
$table->string('assistance_number', 50)->nullable();
$table->morphs('assitanceable')->nullable();
});
Run Code Online (Sandbox Code Playgroud)
但是这个例子在将“->nullable()”赋值给 morph 列时返回 null。
我尝试手动创建 _type 和 _id 并且它工作正常。
手动变形列的示例:
Schema::create('ps_assistances', function (Blueprint $table) {
$table->bigIncrements('id');
$table->string('assistance_number', 50)->nullable();
$table->string('assitanceable_type')->nullable();
$table->unsignedBigInteger('assitanceable_id')->nullable();
});
Run Code Online (Sandbox Code Playgroud)
我想知道是否存在更好的方法来实现一对一的多态关系可空。
Nic*_*ank 17
nullableMorphs 应该为你处理这个
例如:
Schema::create('ps_assistances', function (Blueprint $table) {
$table->bigIncrements('id');
$table->string('assistance_number', 50)->nullable();
$table->nullableMorphs('assitanceable');
});
Run Code Online (Sandbox Code Playgroud)
eyl*_*lay 11
您可以使用nullableMorphs
$table->nullableMorphs('assitanceable');
Run Code Online (Sandbox Code Playgroud)
https://laravel.com/docs/9.x/migrations#column-method-nullableMorphs