[英]Laravel Backpack - Show specific attribute from relationship function
听起来选择列非常适合您。 只需在 EntityCrudController 的setup()
方法中使用它,如下所示:
$this->crud->addColumn([
// 1-n relationship
'label' => "User", // Table column heading
'type' => "select",
'name' => 'user_id', // the column that contains the ID of that connected entity;
'entity' => 'user', // the method that defines the relationship in your Model
'attribute' => "user", // foreign key attribute that is shown to user
'model' => "App\Models\User", // foreign key model
]);
“属性”告诉 CRUD 在表格单元格中显示什么(名称、id 等)。
如果你这样做:
$user = $comment->user->user;
你会得到“测试”; (从你的例子)
这可能看起来令人困惑,因为您的 User 模型具有 user 属性。 也许您可以将其称为“名称”而不是“用户”。 这样你就可以调用它:
$username = $comment->user->name;
请记住在调用相关模型上的属性之前检查关系是否存在。
if(!is_null($comment->user)) {
$username = $comment->user->user;
}
或者:
$username = !is_null($comment->user) ? $comment->user->user : 'No user';
如果你需要从更深层次的关系中获取一些字段,你可以使用闭包列类型:
$this->crud->addColumn([
'label' => trans('backend.column_names.agency_linked_service'),
'name' => 'agency_service_id',
'type' => 'closure',
'function' => function (AgencyLinkedServices $entry) {
return $entry->agencyService->agencyCategory->title;
}
]);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.