SQL Query to exclude records with empty upload fields

5 posts by 3 authors in: Forums > CMS Builder
Last Post: March 24, 2022   (RSS)

By pgplast - March 20, 2022

I am building an application for which it is important to be able to limit my returned record set to only those that have values in an field of type 'upload'.

For example, I have a table that has a field called "cover_art" that is an upload field accepting images. Now once one has a recordset, it is simple enough to see if the cover_art upload field is empty. However, for my purpose, I need to limit the query from the outset, so that it never returns records with no cover_art images.

I have tried 

"where"  => "cover_art IS NOT NULL AND cover_art <> ''   "

but this returns the error: Unknown column 'cover_art' in 'where clause'

If I run a strsaight sql statement in the SQL console such as:

SELECT title FROM cmsb_tv_shows WHERE cover_art <>'' 

I get the same error

It seems that fields of type "upload" cannot be addressed in this way.

In order for my page to work I need to pull a random record from the table, but only from among those records that have an upload in the "cover_art" field.

How to do this???

Thanks.

pgplast

By daniel - March 21, 2022

Hi pgplast,

As you've noticed, upload fields are not handled directly in the table, so can't be queried like this. Essentially each uploaded image in the field is stored as its own record in a separate uploads table, so instead of checking for "empty field" we can look for "has any records in uploads table."

To do this, you can use a left join on the "uploads" table and match it up with the record num, then narrow it down to the correct table name and field name. Something like this:

  list($records, $metaData) = getRecords(array(
    'tableName'   => 'tv_shows',
    'leftJoin' => [
      'uploads' => 'ON tv_shows.num = uploads.recordNum'
    ],
    'where' => "uploads.tableName = 'tv_shows' AND uploads.fieldName = 'cover_art'",
    'groupBy' => 'tv_shows.num',
  ));

If you're ever curious, you can visit "/cmsb/admin.php?menu=uploads" in your CMSB admin to view the records in the uploads table, which may give some better context around how the data is structured and how to access it.

Let me know if you're able to get this to work, or if you have any other questions.

Thanks!

Daniel
Technical Lead
interactivetools.com

By pgplast - March 21, 2022

Thank you for the education, Daniel.

A big help!

By pgplast - March 24, 2022

Thanks, Codee. That is a potentially useful solution for a similar problem as mine. In this instance, it would not meet our needs.

However, I will keep that in my back pocket for potential future use!

Thanks again.

pgplast