简体   繁体   English

Laravel Backpack - 从关系函数中显示特定属性

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

I have the registered Comment model which has a User reference, like this:我有注册的Comment模型,它有一个User参考,像这样:

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

This function returns an instance of a User , and that's correct, but I don't know how to register the User column the get que user property using Backpack.此函数返回一个User的实例,这是正确的,但我不知道如何使用 Backpack 将User列注册为 get que user属性。 Instead, I'm get a JSON representation of my model:相反,我得到了我的模型的 JSON 表示:

在此处输入图像描述

So, how do I get a specific field from my relationship function ?那么,如何从关系函数中获取特定字段

Sounds like the select column is a perfect match for you.听起来选择列非常适合您。 Just use it in your EntityCrudController's setup() method, like so:只需在 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
]);

The "attribute" tells CRUD what to show in the table cell (the name, the id, etc). “属性”告诉 CRUD 在表格单元格中显示什么(名称、id 等)。

If you do:如果你这样做:

$user = $comment->user->user;

You'll get 'test';你会得到“测试”; (from your example) (从你的例子)

It may seem confusing because your User model has a user attribute.这可能看起来令人困惑,因为您的 User 模型具有 user 属性。 Maybe you can call it 'name' instead of 'user'.也许您可以将其称为“名称”而不是“用户”。 That way you'll call it:这样你就可以调用它:

$username = $comment->user->name;

Remember to check if the relationship exists before calling a property on the related model.请记住在调用相关模型上的属性之前检查关系是否存在。

if(!is_null($comment->user)) {
    $username = $comment->user->user;
}

Or:或者:

$username = !is_null($comment->user) ? $comment->user->user : 'No user';

If you need to get some field from deeper relation, you can use closure column type:如果你需要从更深层次的关系中获取一些字段,你可以使用闭包列类型:

$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