Views: 2590
Last Modified: 29.03.2022
  • foreach

    Base collection class implements the \Iterator interface, allowing to get items:

    $books = \Bitrix\Main\Test\Typography\BookTable::getList()
    	->fetchCollection();
    
    foreach ($books as $book)
    {
    	// ...
    }
  • getAll, getByPrimary

    Collection items can also be fetched directly. The method getAll returns all the contained objects as an array:

    $books = \Bitrix\Main\Test\Typography\BookTable::getList()
    	->fetchCollection();
    
    $bookObjects = $books->getAll();
    
    echo $bookObjects[0]->getId();
    // prints ID value for the first object
    

    The method getByPrimary gets specific objects, contained in the collection:

    // 1. example with standard primary key
    $books = \Bitrix\Main\Test\Typography\BookTable::getList()
    		->fetchCollection();
    	
    $book = $books->getByPrimary(1);
    // book with ID=1
    
    // 2. example with composite primary key
    $booksToAuthor = \Bitrix\Main\Test\Typography\BookAuthorTable::getList()
    	->fetchCollection();
    
    $bookToAuthor = $booksToAuthor->getByPrimary(
    	['BOOK_ID' => 2, 'AUTHOR_ID' => 18]
    );
    // assigns relations for book object with ID=2 and author with ID=18
    
  • has, hasByPrimary

    You can check availability of specific object in the collection using the method has:

    $book1 = \Bitrix\Main\Test\Typography\Book::wakeUp(1);
    $book2 = \Bitrix\Main\Test\Typography\Book::wakeUp(2);
    
    $books = \Bitrix\Main\Test\Typography\BookTable::query()
    	->addSelect('*')
    	->whereIn('ID', [2, 3, 4])
    	->fetchCollection();
    
    var_dump($books->has($book1));
    // prints false
    
    var_dump($books->has($book2));
    // prints true
    

    Similarly, the method hasByPrimary is convenient for checking by the primary key:

    $books = \Bitrix\Main\Test\Typography\BookTable::query()
    	->addSelect('*')
    	->whereIn('ID', [2, 3, 4])
    	->fetchCollection();
    
    var_dump($books->hasByPrimary(1));
    // prints false
    
    var_dump($books->hasByPrimary(2));
    // prints true
    
  • add, []

    Objects are added by the method add and interface ArrayAccess, allowing to use the structure []:

    $book1 = \Bitrix\Main\Test\Typography\Book::wakeUp(1);
    
    $books = \Bitrix\Main\Test\Typography\BookTable::query()
    	->addSelect('*')
    	->whereIn('ID', [2, 3, 4])
    	->fetchCollection();
    
    $books->add($book1);
    // or
    $books[] = $book1;
  • remove, removeByPrimary

    You can delete object from collection either directly or by specifying the primary key:

    $book1 = \Bitrix\Main\Test\Typography\Book::wakeUp(1);
    
    $books = \Bitrix\Main\Test\Typography\BookTable::getList()
    	->fetchCollection();
    
    $books->remove($book1);
    // book with ID=1 is deleted from collection
    
    $books->removeByPrimary(2);
    // book with ID=2 is deleted from collection
    




Courses developed by Bitrix24