簡體   English   中英

Laravel Backpack - 從關系函數中顯示特定屬性

[英]Laravel Backpack - Show specific attribute from relationship function

我有注冊的Comment模型,它有一個User參考,像這樣:

public function user() {
    return $this->belongsTo('App\User');
}

此函數返回一個User的實例,這是正確的,但我不知道如何使用 Backpack 將User列注冊為 get que user屬性。 相反,我得到了我的模型的 JSON 表示:

在此處輸入圖像描述

那么,如何從關系函數中獲取特定字段

聽起來選擇列非常適合您。 只需在 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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM