Magento2: Load Model Data By Another Field
You need to use collections for that:
$messages = $objectManager->create('Custom\Module\Model\ResourceModel\Messages\Collection')->addFieldToFilter('posts_id', $this->getRequest()->getParam('id'));
This is assuming you have created a collection resource model for your Messages
entity.
NB: please try to avoid using the Object Manager directly
Instead you can inject the collection class in your constructor:
protected $_messagesCollection;
public function __construct(
...
\Custom\Module\Model\ResourceModel\Messages\Collection $messagesCollection,
...)
{
...
$this->_messagesCollection = $messagesCollection;
}
And then you can use your variable directly in your code:
$messages = $this->_messagesCollection->addFieldToFilter('posts_id', $this->getRequest()->getParam('id'));
You don't need to use collection for that.
Just call the load
function, with a second parameter, the field.
Inject the factory in the construct where you need to retrieve your model
protected $messagesFactory;
public function __construct(\Custom\Module\Model\MessagesFactory $messagesFactory){
$this->_messagesFactory = $messagesFactory;
}
And then, where you want it :
$messages_model = $this->_messagesFactory->create();
$messages_model->load($the_id,'posts_id');
if(!$messages_model->getId()){
echo "not found";
}