Laravel Nova:如何显示MorphTo字段的相关资源中的所有字段?

时间:2019-05-04 19:35:23

标签: php laravel laravel-nova

我写代码:

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();
        });
    }

它显示如下:

enter image description here

但是对于用户而言,此显示将很方便:

enter image description here

如何显示?

或像MorphTo一样显示MorphOne

class User extends Resource {

    public function fields(Request $request) {
        return [
            MorphOne::make('File'),
            ];
    }

我可以做类似的事情吗?

enter image description here

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()),

        ];
    }

但显示了所有模型字段:

enter image description here

但是我只想显示资源中描述的字段。

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) ),
        ];
    }

0 个答案:

没有答案