Laravel - 更改#appends数组中包含的对象属性字段

3

我正在尝试更改作为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属性,但无法更改urlslug属性。我已经检查了post->guidpost->slug属性,并得到了它们的值,但是item对象属性没有被更改?
更新:
刚刚意识到slug字段在模型的#appends数组中,而不在#attributes数组中。有没有办法为给定的对象更改它?

它们可能是“受保护”的属性吗? - Martin Bean
我在laravel中没有设置任何内容,但是我从WP数据库获取数据,并且在期望使用dd($item)查看对象时,我发现它有一个#guarded: array:1 [ 0 => "*" ]。 - Leff
你能发布一下你的模型属性吗? - TecBeast
我已经更新了我的问题。 - Leff
1个回答

2

添加可填写字段:

protected $fillable = ['url', 'slug']

然后你可以执行以下操作:
$item->update(["post_title" => $post->post_title,
               "url" => $post->guid
               // etc...
]);

或者这样做:
$item->post_title = $post->post_title;
$item->url = $post->guis;
$item->save();

我不是试图将其保存到数据库中,我只是在发送响应之前尝试对其进行更改。 - Leff

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接