PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Tuesday, March 15, 2022

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

 March 15, 2022     cakephp, cakephp-3.0, mysql     No comments   

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
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home
View mobile version

0 Comments:

Post a Comment

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

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing