0

I have the following database table:

id     - PK (Auto Increment)
hash   - a unique index the value here is filled using the function "uniqid()"  
title  - string..

I want to query from table using a hash value not the id. Is this practice will load the server, as I know is the best way to get some row from the database table especially the one who contain high number of rows is searching using a primary key:

$row = Book::find(1);

Or I can use the following eloquent builder without worry of making unnecessary load to database server because he hash is set as a unique key:

$row = Book::where('hash',$hashFromAPiRequest)->first();

There is a package named laravel Scout, I am not sure if I really need to use it or not.

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Q8root
  • 1,243
  • 3
  • 25
  • 48
  • This really has nothing to do with Laravel. Assuming, MySQL, the fastest way is by key, as InnoDB implements a clustered index by PK. With that said, access by the indexed hash is highly efficient. – gview May 24 '20 at 02:33

1 Answers1

1

You don't need to use Laravel Scout for this. A simple where condition will suffice. As long as the hash column is indexed, your query will not load up the server.

However, since you mentioned unnecessary load, you can still optimized a tiny bit here by using select(). Please use only those columns that you really need otherwise you are sending/consuming additional bytes of data.

$row = Book::select('id', 'title')->where('hash',$hashFromAPiRequest)->first();

You can also check out Laravel use mysql indexing if you want to learn more about optimizing.

Digvijay
  • 7,836
  • 3
  • 32
  • 53