如何 return 原始值而不是 laravel 集合中的关系对象

How to return raw value instead of relationship object in a laravel collection

我正在努力获取 LengthAwarePaginator 对象中的关系值,我正在尝试使用集合 transform 方法并覆盖 created_by 属性来获取记录创建者的名称,但我得到了整个对象,而不仅仅是名称:

    $data = $this->smsTemplateRepository->getAll($page, $pageSize, $filter, $sortBy, $paginate);
    $data->transform(function ($item, $key) {
          $item['created_by'] = $item->createdBy->name;
          return $item;
    });

这就是我在前端得到的结果

code: "eS5Zx39jXq"
created_at: "2022-05-13T15:55:39.000000Z"
created_by: {id: 2, legacy_user_ref: "bece66c5efe01a4a4fae87650f1072a9", user_type: "employee", client_id: null,…}
id: 5
message: "lIu72gF7S4 {{ worker_name }}2SiQPJAgFrzMw1fzPfqtGSYLY4hgzC1ZOBFaKQGG8T21VSWjmn bye."
name: "fb71e78X07 rQ7ChsUQNr"
sms_legacy_ref: "H6O1BxFBDT"
updated_at: "2022-05-13T15:55:39.000000Z"
updated_by: 2

我期待 created_by: 'Name Lastname',

任何想法,谢谢!!

一旦你设置了你想要的属性就可以卸载关系

$data = $this->smsTemplateRepository->getAll($page, $pageSize, $filter, $sortBy, $paginate);
    $data->transform(function ($item, $key) {
          $createdBy = $item->createdBy->name;
          $item->unsetRelation('createdBy');
          $item->created_by = $createdBy;
          return $item;
    });