cakephp 3 query is not executing

523 views Asked by At

I am new in cakephp3. I am trying to execute below query but its showing me error.

$lifeinsurances = TableRegistry::get('LifeInsurances')->find("all");
$life_insurances = $lifeinsurances->find()
    ->join([
        'table' => 'institutions',
        'alias' => 'institutions',
        'type' => 'LEFT',
        'conditions' => 'institutions.id = LifeInsurances.institute_id',
    ]);

I have fixed previous query. Now I am getting only one table data.

EDIT

Now I created association using cake bake. But a new error showing this time. Below is my code.

public function index() { 
    $this->paginate = [
        'contain' => ['Institutions']
    ];
    $lifeInsurances = $this->paginate($this->LifeInsurances);
    $this->set(compact('lifeInsurances'));
    $this->set('_serialize', ['lifeInsurances']);
}

Internal server error

if I remove

 $this->paginate = [
        'contain' => ['Institutions']
    ];
    $lifeInsurances = $this->paginate($this->LifeInsurances);

error stop showing

2

There are 2 answers

1
Greg Schmidt On

If you have your table associations set up correctly (which they should be automatically if you used bake to create your code), you should be able to simply say:

$lifeinsurances = TableRegistry::get('LifeInsurances')
    ->find('all')
    ->contain(['Institutions']);
0
Ankush Tanwar On

If you want contain to work , you need to define associations in your respective Models (lies in Table Folder in case of cakephp 3.x). Since you are saying that you have baked the models, Ensure that relationships are defined in the respective models.

That may be the reason that it is throwing error.

Normally when you have created all the tables in your database , then you should bake the models. Because adding table after you have baked the models do not define relationships in the new models and you have to explicitly define it.

Have a look at this - How associations get defined when code is baked in Cakephp

Also check the naming conventions of the foreign keys defined in the tables. Cakephp use this naming conventions to define the relationships between models.

Furthermore it would be great if you can post the error log, so as to find out more exact solution to your problem.