2017-06-29 37 views
2

我正在嘗試更改作爲該函數的json響應返回的對象的屬性。我沒有試圖保存它並將它保存到DB,只是在將它作爲api響應發送之前進行更改。這是一段代碼,我這樣做:Laravel - 更改#appends數組內的對象屬性字段

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陣列英寸有沒有辦法改變它給定的對象?

+0

是否有可能他們是_guarded_屬性? –

+0

我沒有在laravel中設置任何東西,但我從WP數據庫獲取數據,並期望使用dd($ item)對象'''我看到它有#guarded:array:1 [ 0 =>「*」 ] – Leff

+0

你能發佈你所有的模型屬性嗎? – TecBeast

回答

1

添加字段是可填寫:

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(); 
+0

我不是試圖將它保存到數據庫,我只是試圖在將它作爲響應發送之前進行更改 – Leff