[英]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.