Tuesday, March 15, 2022

[FIXED] How to Fetch data from two tables in cakephp 3

Issue

I am new in cakephp and my table like:

city
id | name
1  | city1
2  | city2

state
id | name | cityid
1  |state1| 2

so how do i get the city name if i having state id. In controller i have code like this.

public function getCity()
    {
        if( $this->request->is('ajax') ) {
        $this->autoRender = false;
    }

    if ($this->request->isPost()) {
        $sId= $this->request->data['stateid'];
    }
    }

In the $sId i get value so how do i write query.


Solution

If you have a BelongsTo relationship between both Model, you just have to do a query on the States which contains City:

public function getCity()
{
    if( $this->request->is('ajax') ) {
        $this->autoRender = false;
    }

    if ($this->request->isPost()) {
        $stateEntity = $this->States->find('all')
            ->where(['id' => $this->request->data['stateid']])
            ->contain(['Cities'])
            ->first();
        // Now the State Object contains City 
        $cityName = $stateEntity->city->name;
    }
}

To create this relationship you need to do like this:

class StatesTable extends Table
{

    public function initialize(array $config)
    {
        $this->belongsTo('Cities')
            ->setForeignKey('city_id')
            ->setJoinType('INNER');
    }
}


Answered By - SamHecquet

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.