【问题标题】:Laravel Backpack - Inline create, relationship not being added on DBLaravel Backpack - 内联创建,未在数据库中添加关系
【发布时间】:2021-06-20 02:42:53
【问题描述】:

我正在尝试 4.1 新功能“内联创建”,但我似乎无法关联所创建项目的 ID。让我解释一下我在做什么/我想要什么:

我有“文件夹”,里面有“章节”(所以 1-n 关系)。

我的代码:

    CRUD::addField([  //Folder crud
            'name' => 'chapters', 
            'type' => 'relationship',
            'label' => 'Unidad',
            'model' => "App\Models\Chapter",
            'inline_create' => [
                'entity' => 'chapter',
                'modal_class' => 'modal-dialog modal-xl',
                'modal_route' => route('chapter-inline-create'),
                'create_route' =>  route('chapter-inline-create-save'),
            ]
        ]);

    protected function setupCreateOperation() //Chapter crud
    {
        CRUD::setValidation(ChapterRequest::class);

        CRUD::addField([
            'name' => 'name', 
            'type' => 'text', 
            'label' => 'Nombre'
        ]);
    }

    public function chapters() //Folder model
    {
        return $this->hasMany(Chapter::class);
    }

    public function folder() //Chapter model
    {
        return $this->belongsTo(Folder::class);
    }

它创建主要项目和相关项目没有问题,但它实际上并没有在任何时候将它们关联到数据库中。

任何线索我可能做错了什么?遵循文档,但似乎无法使其工作。

谢谢。

【问题讨论】:

  • 成功了吗?基本上,我有同样的问题。不过有趣的是,当您尝试从子代内联创建父代时,它会起作用。在这种情况下,如果您从 chapter 内部创建 folder 它可以工作,但是当您尝试从 folder 创建 chapter 时,它会永远挂起。

标签: php laravel laravel-backpack eloquent-relationship


【解决方案1】:

你在 db 中有正确的列名吗?使关系成为可能的列,即在文件夹表中,您应该有一个名为 chapter_name 或 chapter_id 的列,以标识文件夹所属的章节。

此外,如果这些列不遵循 laravel 约定,则需要在模型中实现关系时将它们添加为第二个和第三个参数

更多详情在这里https://laravel.com/docs/8.x/eloquent-relationships#one-to-many

【讨论】:

  • 我的表:Schema::create('folders', function (Blueprint $table) { $table->increments('id'); $table->string('name'); $table->text('chapters'); $table->timestamps(); });Schema::create('chapters', function (Blueprint $table) { $table->increments('id'); $table->string('name'); $table->unsignedInteger('folder_id')->nullable(); $table->timestamps(); $table->foreign('folder_id')->references('id')->on('folders')->onDelete('cascade'); });
猜你喜欢
  • 1970-01-01
  • 2017-05-10
  • 1970-01-01
  • 2020-02-02
  • 2017-12-03
  • 1970-01-01
  • 2020-12-04
  • 1970-01-01
  • 2023-03-07
相关资源
最近更新 更多