We have two approaches to find if the record exists in database or not

First

$select = $this->bookResource->getConnection()->select()
->distinct()
->from(
    $this->bookResource->getMainTable(),
    "author_id"
)
->where("author_id = ?", $authorId);
if ($this->bookResource->getConnection()->fetchOne($select)) {
      //record exist
}

second

$bookCollection->addFieldToSelect('author_id')
    ->addFieldToFilter("author_id", $authorId);
if ($bookCollection->getSize()){
    // record exist
}

which one to use and why

有帮助吗?

解决方案

I would use the first one but with a limit.

$select = $this->bookResource->getConnection()->select()
->distinct()
->from(
    $this->bookResource->getMainTable(),
    "author_id"
)
->where("author_id = ?", $authorId)
->limit(1);

This will run a query like SELECT DISTINCT(..) FROM ... WHERE author_id = ... LIMIT 1.

Without the limit, if there are multiple rows matching your criteria, all will be retrieved from the db and one will be returned.
The second approach, with getSize runs a query like SELECT COUNT(*) from ... where.... it may run slow if you have a lot of records.

But if you want to respect the Law Of Demeter you can use a combination of the 2.

$bookCollection->addFieldToSelect('author_id')
    ->addFieldToFilter("author_id", $authorId)
    ->setPageSize(1)
    ->setCurPage(1);
$book = $bookCollection->getFisrtItem();
if ($book->getId()) {
    //a row exists
} else {
    //there is no row for the selected author.
}

其他提示

class testIfExist
{
/**
 * @var ResourceConnection
 */
private $resourceConnection;

/**
 * @param ResourceConnection $resourceConnection
 */
public function __construct (
    ResourceConnection $resourceConnection
) {
    $this->resourceConnection = $resourceConnection;
}

/**
 * @param string $pageId
 * @return bool
 */
public function execute(string $id): bool
{
    $connection = $this->resourceConnection->getConnection();

    $tableName = $this->resourceConnection->getTableName('table-name-here');

    $qry = $connection->select()
        ->from($tableName)
        ->where('entity_id_of_table = ?', $id);

    return (bool)$connection->fetchOne($qry);
}
}

easy class to call

Cheers

许可以下: CC-BY-SA归因
scroll top