微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

laravel nova - 如何制作一个有限制的自引用模型

如何解决laravel nova - 如何制作一个有限制的自引用模型

我有一个基于下表的 Laravel 模型:

public function up()
{
    Schema::create('things',function (Blueprint $table) {
        $table->id();
        $table->timestamps();
        $table->string('label');
        $table->foreignId('user_id')->nullable()->constrained('users');
    });

还有一个数据透视表,使它成为多对多的自引用模型。

  public function up()
  {
    Schema::create('thing_thing',function (Blueprint $table) {
      $table->id();
      $table->timestamps();
      $table->string('message')->nullable();
      $table->unsignedBigInteger('parent_id')->nullable();
      $table->unsignedBigInteger('child_id')->nullable();
      $table->unique(['parent_id','child_id']);
      $table->foreign('parent_id')->references('id')->on('things')->onDelete('cascade');
      $table->foreign('child_id')->references('id')->on('things')->onDelete('cascade');
    });
  }

当我创建链接到此模型的 Nova 资源时,我想限制将 thing 附加到自身。因此,例如,带有 thingid = 1 不会出现在带有 id = 1 的事物的附件的选择器中。这是我的 Nova 资源:

  public function fields(Request $request)
  {
    return [
      ID::make(__('ID'),'id')->sortable(),Text::make('label'),ID::make('user_id')->hideWhenUpdating()->hideWhenCreating(),BelongsToMany::make('Trees','trees'),BelongsToMany::make('Things','childOf'),'parentOf')
    ];
  }

解决方法

您可以通过 App\Nova\RessourcerelatableQuery 方法解决此问题。只需覆盖您的 nova 资源中的方法:

class Thing extends Resource {

    // ...

    public static function relatableQuery(NovaRequest $request,$query)
    {
        // Make sure you only apply the filter to the things-things relatable query
        if( $request->route('resource') === 'things' ) {
            $currentId = $request->route('resourceId');
            $query->where('id','!=',$currentId);
        }
        return $query
    }
}

您可以找到文档 here

此外,您可能希望在迁移中使 parent_idchild_id 的列组合唯一,以进一步确保唯一性。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。