Laravel Backpack - 显示关系功能的特定属性

I have the registered Comment model which has a User reference, like this:

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. Instead, I'm get a JSON representation of my model:

enter image description here

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:

$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).

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. 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';