首页 > 解决方案 > Laravel Backpack:在 Show Operation 中显示多对多关系

问题描述

在文档中找不到这个。

是否有任何标准方法,无需创建自定义小部件或覆盖视图模板,在 Laravel 的 Backpack 中的 CRUD 的 showOperation 中显示多对多关系?如果答案是否定的,那么您的实施方法是什么?

假设我有一个课程模型和一个用户模型,两者之间存在多对多

class Course extends Model
{
    public function students()
    {
        return $this->belongsToMany(User::class, 'course_students');
    }
}


class User extends Model
{
    public function courses()
    {
        return $this->belongsToMany(Course::class, 'course_students');
    }
}

在课程的显示操作中。如何显示所有学生的表格?

标签: laravel-backpack

解决方案


实际上,您可以为此使用关系列

摘抄:

输出相关条目,无论关系如何:

1-n 关系 - 输出其一个连接实体的名称;

nn 关系 - 枚举其所有连接实体的名称;

其名称和定义与关系字段类型相同:

[  
   // any type of relationship
   'name'         => 'tags', // name of relationship method in the model
   'type'         => 'relationship',
   'label'        => 'Tags', // Table column heading
   // OPTIONAL
   // 'entity'    => 'tags', // the method that defines the relationship in your Model
   // 'attribute' => 'name', // foreign key attribute that is shown to user
   // 'model'     => App\Models\Category::class, // foreign key model
],

Backpack 尝试猜测要为相关项目显示哪个属性。最终用户会认为是独一无二的东西。如果它是“名称”或“标题”之类的常见内容,它会猜到。如果没有,您可以在列定义中手动指定属性,也可以添加 public $identifiableAttribute = 'column_name'; 到您的模型,Backpack 将使用该列作为用户发现可识别的列。它将在这里使用它,并且它将在您没有明确要求不同属性的任何地方使用它。


推荐阅读