我写代码:
class File extends Resource {
public function fields(Request $request) {
return [
MorphTo::make('Fileable')->types([
User::class,
])
];
}
class File extends Model {
public function fileable() {
return $this->morphTo();
}
class CreateFilesTable extends Migration {
public function up() {
Schema::create('files', function (Blueprint $table) {
$table->bigIncrements('id');
$table->morphs('fileable');
$table->timestamps();
});
}
它显示如下:
但是对于用户而言,此显示将很方便:
如何显示?
或像MorphTo
一样显示MorphOne
:
class User extends Resource {
public function fields(Request $request) {
return [
MorphOne::make('File'),
];
}
我可以做类似的事情吗?
Lifehack#1:
protected function panel(): array {
$fs = [];
foreach($this->model()->fileable->getAttributes() as $k => $v) {
$fs[] = Text::make($k, null, function() use($v) { return $v;});
}
return $fs;
}
public function fields(Request $request) {
return [
ID::make()->sortable(),
new Panel('Information', $this->panel()),
];
}
但显示了所有模型字段:
但是我只想显示资源中描述的字段。
Lifehack#2:
protected function panel(Request $request): array {
$fs = [];
$name = (new \ReflectionClass(get_class($this->model()->detailable)))->getShortName();
$res = "App\Nova\\{$name}";
$r = new $res($this->model()->detailable);
foreach($r->fields($request) as $k => $v) {
$v->attribute = 'detailable->' . $v->attribute;
$v->onlyOnDetail();
$fs[] = $v;
}
return $fs;
}
public function fields(Request $request) {
return [
new Panel('Information', $this->panel($request) ),
];
}