2016-04-26 1 views
0

指定された条件を満たすエンティティを削除します。どうしたらいいですか?実際にあなたができる前に最初にあなたのエンティティを取得する必要が未定義のメソッドのDrupal \コア\ Configを\エンティティ\クエリー\クエリへの呼び出し::削除()いくつかの条件でエンティティを削除するDrupal 8

答えて

0

$current_user = \Drupal::currentUser()->id(); 
$storage = \Drupal::entityManager()->getStorage('context'); 

$query = $storage->getQuery()->condition('user_id', $current_user); 

$query = $storage->getQuery()->delete(); 
$query->condition('user_id', $current_user); 
$query->condition('key_text', $key); 

$query->execute(); 

しかしコードを返します:致命的なエラー削除してください。このメソッドは、それらの更新や情報の取得にも必要です。以下のコードが役に立ちますようお願いいたします。

$current_user = \Drupal::currentUser()->id();  

$ids = \Drupal::entityQuery('context') 
      ->condition('user_id', $current_user) 
      ->execute(); 

$itemsToDelete = $this->entityTypeManager->getStorage('context') 
      ->loadMultiple($ids); 


foreach ($itemsToDelete as $item) { 
    $item->delete(); 
} 
0

エンティティを照会するには、entityQueryを使用できます。以下の例ではこれを使用しています。

// Get all users with email containing "xyz" 
$query = \Drupal::entityQuery('user') 
    ->condition('mail', "XYZ", 'CONTAINS'); 
$uids = $query->execute(); 

// Load these entities ($uids) in our case using storage controller. 
// We call loadMultiple method and give $uids array as argument.  
$itemsToDelete = \Drupal::entityTypeManager()->getStorage('user') 
    ->loadMultiple($uids); 

// Loop through our entities and deleting them by calling by delete method. 
foreach ($itemsToDelete as $item) { 
    $item->delete(); 
} 
+2

このコードスニペットは歓迎されていますが、いくつかの助けを提供するかもしれませんが、* how *と* why *の説明があれば大幅に改善されます(// meta.stackexchange.com/q/114762)これは問題を解決します。あなたが今質問している人だけでなく、将来読者のための質問に答えていることを忘れないでください!説明を追加するためにあなたの答えを[編集]し、どんな制限と前提が適用されるかを示してください。 –

0

エラー・メッセージが、あなたの設定エンティティを照会するため使用しているクラスがdelete()メソッドを持っていないという事実に起因しています。これはコンテンツエンティティにも当てはまります。 delete()メソッドはエンティティによって実装されるため、正しいコードは次のようになります。

$storage = \Drupal::entityTypeManager()->getStorage('context'); 
$query = $storage->getQuery(); 

$ids = $query->condition('user_id', $current_user) 
    ->condition('key_text', $key) 
    ->execute(); 

foreach ($storage->loadMultiple($ids) as $entity) { 
    $entity->delete(); 
} 

entity.query service deprecated in favor of EntityStorageInterface::getQuery()を参照してください。

0

複数のエンティティを削除するには、エンティティストレージのdelete()メソッドを使用します。すべてを繰り返す必要はありません。 https://stackoverflow.com/a/43786945/442022から撮影

$query = \Drupal::entityQuery('taxonomy_term'); 
$query->condition('vid', 'tags'); 
$tids = $query->execute(); 

$storage_handler = \Drupal::entityTypeManager()->getStorage($entity_type); 
$entities = $storage_handler->loadMultiple($tids); 
$storage_handler->delete($entities); 

関連する問題