我正在尝试与belongsTo
范围直接建立->withTrashed()
关系。
这是软删除的模型:
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
class ContractType extends Model
{
use SoftDeletes;
}
这是尝试访问合同类型的模型:
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class Employee extends Model
{
protected $fillable = [
'contract_type_id',
'name'
];
public function contract_type()
{
return $this->belongsTo(ContractType::class);
}
public function contract_type_with_trashed()
{
return $this->belongsTo(ContractType::class)->withTrashed();
}
}
这是我查询这些关系时得到的:
$employee = Employee::first(); // has a contract_type_id of 1
dd($employee->contract_type, $employee->contract_type_with_trashed);
/*
ContractType {#722 ▼
#dates: array:2 [▶]
#connection: "mysql"
#table: "contract_types"
#primaryKey: "id"
#keyType: "int"
+incrementing: true
#with: []
#withCount: []
#perPage: 15
+exists: true
+wasRecentlyCreated: false
#attributes: array:7 [▶]
#original: array:7 [▶]
#changes: []
#casts: []
#dateFormat: null
#appends: []
#dispatchesEvents: []
#observables: []
#relations: []
#touches: []
+timestamps: true
#hidden: []
#visible: []
#fillable: []
#guarded: array:1 [▶]
#forceDeleting: false
}
null
*/
实际上没有删除任何ContractType
,并且contract_types
表中确实有deleted_at
列。
我该如何使用它?
[编辑]
这是contract_types
表迁移:
Schema::create('contract_types', function (Blueprint $table) {
$table->tinyIncrements('id');
$table->string('name');
$table->timestamps();
$table->softDeletes();
});
以及employees
表迁移:
Schema::create('employees', function (Blueprint $table) {
$table->bigIncrements('id');
$table->unsignedTinyInteger('contract_type_id');
$table->string('name');
$table->timestamps();
$table->foreign('contract_type_id')->references('id')->on('contract_types')->onDelete('cascade');
);
结果,我的deleted_at
列符合预期。
我可以补充一点,$employee->contract_type()->withTrashed()->get()
可以很好地工作,但是当它在关系中时,它就行不通了。