skip to Main Content

I want to save some data from an external source that has no id other than the data itself (eg. Red, Used, Volvo etc. from the ebay api).

So I have set up my tables like so:

aspectHeaders
id INT AUTO_INCREMENT PRIMARY KEY
name varchar(30)
UNIQUE KEY `NAME`(`name`)

aspects
id INT AUTO_INCREMENT PRIMARY KEY
name varchar(30)
aspectHeader_id INT
UNIQUE KEY `DETAIL` (`aspectHeader_id`,`name`)

aspectHeaders would contain:

7 Manufacturer

and aspects would contain:

1 Volvo 7

So in 2 stages I could check for the existence of any given data in either table and then insert it if it doesn’t exist. But my question is can I do it in 1 stage? That is, is there code to check if the data exists and insert it if not and either way return the id?

Hope this is verbose enough.

Thanks

2

Answers


  1. If by “code” you mean a single MySQL statement, I don’t think there is. Or at least I don’t think there is without making an overly-complicated multi-query query.

    Just make an alreadyExists() method (or something) and check before insert – something like:

    if(!$this->MyModel->alreadyExists($data)) {
        //do insert here
    }
    
    Login or Signup to reply.
  2. I usually use a method like touch() for this that does all the magic internally.

    // always returns id (or false on failure)
    public function touch($data) {
        // check if it already exists
        if (exists) {
             // return id and do nothing
        }
        // create() and save()
        // return id or false if invalid data
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search