【问题标题】:Laravel Backpack - Show specific attribute from relationship functionLaravel Backpack - 从关系函数中显示特定属性
【发布时间】:2017-11-04 14:32:55
【问题描述】:

我有注册的Comment 模型,它有一个User 引用,如下所示:

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

此函数返回一个User 的实例,这是正确的,但我不知道如何使用Backpack 注册User 列get que user 属性。相反,我得到了我的模型的 JSON 表示:

那么,如何从我的关系函数中获取特定字段

【问题讨论】:

    标签: php laravel laravel-backpack


    【解决方案1】:

    听起来the select column 非常适合您。只需在 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 等)。

    【讨论】:

    【解决方案2】:

    如果你这样做:

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

    【讨论】:

      猜你喜欢
      • 2016-09-12
      • 2018-12-25
      • 2019-11-15
      • 1970-01-01
      • 1970-01-01
      • 2017-04-02
      • 1970-01-01
      • 1970-01-01
      • 2017-05-03
      相关资源
      最近更新 更多