【发布时间】: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->developer是User实例的集合。另请注意,在定义关系时不需要指定列名,除非它们是非标准的。