我正在尝试更改作为json响应从函数返回的对象的属性。我不想将其保存并持久化到数据库中,只是在将其作为api响应发送之前更改它。这是我执行此操作的代码段:
if ($item->post_title == '') {
$post = $this->findPostId($item);
$item->post_title = $post->post_title;
$item->url = $post->guid;
$item->slug = $post->slug;
$item->setAttribute('post_id', $post->ID);
}
我不明白的是,为什么我可以更改
post_title
属性并设置post_id
属性,但无法更改url
和slug
属性。我已经检查了post->guid
和post->slug
属性,并得到了它们的值,但是item
对象属性没有被更改?更新:
刚刚意识到
slug
字段在模型的#appends
数组中,而不在#attributes
数组中。有没有办法为给定的对象更改它?
dd($item)
查看对象时,我发现它有一个#guarded: array:1 [ 0 => "*" ]。 - Leff