2015-11-02 41 views
0

我試圖通過匹配某些值來刪除laravel關係集合中的項目。問題與答案有一對多的關係。在不返回副本的情況下過濾Laravel集合

之前你問,這些搬遷需要在內存中後完成並存儲到數據庫(這樣我們就可以做一些東西與驗證。)

所以,我用的收集的關係對象給我:

$this->answers->filter(function($answer) use ($answer_ids_to_remove){ 
    return !in_array($answer['id'], $answer_ids_to_remove); 
}); 

但是Collection :: filter返回一個副本,並且不會修改現有的集合。所以,我想這一點:

$this->answers = $this->answers->filter(function($answer) use ($answer_ids_to_remove){ 
    return !in_array($answer['id'], $answer_ids_to_remove); 
}); 

但是我覺得這個任務刪除收集和關係本身之間的聯繫,因爲我開始保存模型時,沒有得到這樣的列,錯誤:

General error: 1 no such column: answers (SQL: update "questions" set "answers" = {"1":{"id":"72","question_id":"117","text":"Answer 2","order":"1"},"2":{"id":"73","question_id":"117","text":"Answer 3","order":"2"},"3":{"text":"Answer 4","question_id":117,"order":3}}, "updated_at" = 2015-11-02 19:18:31 where "id" = 117) 

事實它試圖將它變成JSON,表明它不再承認由於賦值而導致的一對多關係。

我可以在原始集合上運行filter()嗎?或者有沒有辦法將收藏重新鏈接到關係?

回答

0

嘗試使用intersect方法的集合,像這樣:

foreach($answer_ids_to_remove as answer) { 
    $this->answers->intersect($answer) 
} 

與其建造答案一組ID刪除應用的合集本身。

http://laravel.com/docs/5.1/collections#method-intersect

+0

這看起來像它會刪除所有,但第一個匹配項在第一次循環,然後在接下來它會刪除所有其他人。另外,它還會返回數組的副本,而不會修改原始數據。我錯過了什麼嗎? – whiterook6

+0

在實際使用之前從未使用'intersect',我想念你的問題。認爲你不想修改原始集合。對不起。在修改集合的文檔中,我可以看到的唯一一個是'forget()'方法,但它通過其關鍵字從集合中移除了一個項目 –

相關問題