Create function to query the existence of data in a generic way

1
public function consultar_existencia($campo) {
        if ($this->request->is('post')) {
            $this->autoRender = false;
            $this->layout = false;
            $this->loadModel('Client');
            $existe = $this->Client->find('count', array(
                'conditions' => array($campo => $this->request->data('Field')['Data'])));
        }
        echo json_encode($existe);
    }

Hi, I have this function in the controller, I'm going to use it to validate if a data already exists in the DB, the idea is to make some changes, but ps I had some problems I'm going to show you:

public function consultar_existencia($campo) // field is for the field that is going to be compared in the database, and the idea would also be to send you the model you are going to consult by adding something like $model in the parameters, and in this line it is It would load like this: $this->loadModel($model); , and there I think we would go bn, the problem comes in this line:

$existe = $this->Client->find('count', array(
                    'conditions' => array($campo => $this->request->data('Field')['Data']))); 

since in that line a call is made to a specific model, and my question is, is there any way of telling you to check the model currently loaded? something like

$this->getLoadModel()->find('count',  array(
                    'conditions' => array($campo => $this->request->data('Field')['Data']))); 
    
asked by Andrés Vélez 19.06.2018 в 17:32
source

1 answer

0

You can use the famous Variable variables of PHP, in the documentation we found that there are the variable properties and can be used in this way:

$a = 'propiedad';
$this->{$a};

What would be equivalent to doing this:

$this->propiedad;

As you said that you already have the variable $model , you can do the following

$this->{$model}->find('count',  array(
                'conditions' => array($model . '.' . $campo => $this->request->data('Field')['Data'])));
    
answered by 20.06.2018 / 00:28
source