0

I'm building my first Magento 2 module, and I'm a bit stuck.

First of all, this is what I have so far (I'm still fixing the coding standards on all the pages). https://github.com/moloni/magento2

I have a doubt about something a bit simple... How do I get the first row of the table I created?

I made a repository, created all the files for the Tokens model, and I can access the first row using the following:

$collection = $this->getCollection();
if ($collection->getSize()) {
    $this->tokensRow = $collection->getFirstItem();
}

But, since the method getCollection says it will be deprecated, what can I use to the get the first row of a table?

Every method I saw was using the getCollection mehtod, and that's why my doubt.

Also, if I want to read the first row and update the row if it exists, or create a new one if it does not, how can I do so without the getCollection?

Still learning how to properly code for Magento 2.

1 Answer 1

0

Model :

You can use load() if you know your first item id.

public function getFirstItem() {
    $id = "1";
    return $this->_yourmodel->load($id);
}

Collection :

In collection, you can also use limit()

$collection->getSelect()->limit(1); //It's better on performance than getFirstItem()

Update:

Here is how to get a collection :

You need these files:

1. Model

2. Resource Model

3. Resource Model Collection

Then you call your modelFactory to get collection

$col = $this->_modelFactory->create();
$collection = $col->getCollection();

Look the full exemple here

3
  • Well, I can't guarantee that the id is 1 (I can make it be, but I didn't want to guarantee). The problem with collections, is the deprecated notice with getCollection, I got it working with getCollection, but I can't see how to solve this without the getCollection...
    – Sunita
    Commented Dec 11, 2018 at 11:18
  • Also checked out the load, and shows as deprecated
    – Sunita
    Commented Dec 11, 2018 at 13:35
  • Why deprecated ? please look my update
    – PЯINCƎ
    Commented Dec 11, 2018 at 14:13

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.