Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

cakephp 3 fetch all by using table.*

Tags:

php

mysql

cakephp

I am using cakePHP3 query builder to fetch records from two tables using following query, where I want all columns from table1 and selected columns from table2:

$this->loadModel('Table1');
$Table1 = $this->Table1->find('all', array('fields' => array('Table1.*'),'conditions'=>$conditions,'order'=>array('Table1.id'=>'DESC')))->contain(['Table2']);

But I am getting the following error

Error: SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'AS `Table1__*` FROM Table1 Table1 LEFT JOIN Table2 Table2 ON ' at line 1

I am new to CakePHP3.

like image 262
Alisa Avatar asked Apr 11 '26 18:04

Alisa


1 Answers

why not use query builder?

there are many ways to do that

$query= $this->Table1->find('all') 
    ->where($conditions)
    ->order(['Table1.id'=>'DESC'])
    ->contain(['Table2' => [
            'fields' => ['field1', 'field2']
        ]
    ]);

or

$query= $this->Table1->find('all') 
    ->select($this->Table1) // selects all the fields from Table1
    ->select(['Table2.field1', 'Table2.field2']) // selects some fields from Table2
    ->where($conditions)
    ->order(['Table1.id'=>'DESC'])
    ->contain(['Table2']);

or

$query= $this->Table1->find('all') 
    ->where($conditions)
    ->order(['Table1.id'=>'DESC'])
    ->contain(['Table2' => function($q) {
             return $q->select(['field1', 'field2']);
        }
    ]);
like image 112
arilia Avatar answered Apr 14 '26 06:04

arilia



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!