【问题标题】:Backpack for Laravel (select2_multiple)Laravel 的背包(select2_multiple)
【发布时间】:2021-12-10 01:33:52
【问题描述】:

我需要选择多个用户并将名称显示为开发人员。但是我得到了这个错误。

例外 此集合实例上不存在属性 [名称]。 (查看:D:\Laravel\BoomTech\bug-tracker\resources\views\project_issues.blade.php)

应显示用户姓名的代码:

{{ $issue->developer->name }}

问题表:

public function up()
{
    Schema::create('issues', function (Blueprint $table) {
        $table->bigIncrements('id');
        $table->foreignId('project_id');
        $table->foreignId('submitted_by_id');
        $table->foreignId('developer_id');
        $table->string('title', 255);
        $table->string('comment', 255)->nullable();
        $table->mediumText('description');
        $table->text('status');
        $table->text('type');
        $table->timestamp('created_at')->nullable();
        $table->timestamp('updated_at')->nullable();
        $table->timestamp('deleted_at')->nullable();
    });
}

问题用户(数据透视表):

Schema::create('issue_user', function (Blueprint $table) {
        $table->bigIncrements('id');
        $table->foreignId('user_id');
        $table->foreignId('issue_id')->nullable();
        $table->timestamp('created_at')->nullable();
        $table->timestamp('updated_at')->nullable();
    });

问题模型:

public function developer()
{
    return $this->belongsToMany('App\Models\User', 'issue_user', 'issue_id', 'user_id');
}

问题CRUD控制器:

CRUD::addField([    // Select2Multiple = n-n relationship (with pivot table)
        'label' => "Developer",
        'type' => 'select2_multiple',
        'name' => 'developer', // the method that defines the relationship in your Model

        // optional
        'entity' => 'developer', // the method that defines the relationship in your Model
        'model' => "App\Models\User", // foreign key model
        'attribute' => 'name', // foreign key attribute that is shown to user
       'pivot' => false, // on create&update, do you need to add/delete pivot table entries?
    ]);

【问题讨论】:

  • BelongsToMany 建议附加多个User。所以$issue->developerUser 实例的集合。另请注意,在定义关系时不需要指定列名,除非它们是非标准的。

标签: php laravel


【解决方案1】:

这是多对多的关系,所以你需要这样做:

public function developers()
{
    return $this->belongsToMany('App\Models\User', 'issue_user', 'issue_id', 'user_id');
}


@foreach($issue->developers() as $developer)
{{ $developer->name }}
@endforeach

【讨论】:

  • 我仍然收到此错误:ErrorException Attempt to read property "name" on bool(查看:D:\Laravel\BoomTech\bug-tracker\resources\views\project_issues.blade.php)
  • @foreach($issue->developers as $developer) {{ $developer->name }} @endforeach 试试这个
猜你喜欢
  • 2017-12-05
  • 1970-01-01
  • 2017-11-07
  • 1970-01-01
  • 2020-12-16
  • 1970-01-01
  • 2020-09-22
  • 2019-02-17
  • 1970-01-01
相关资源
最近更新 更多