加入表格并显示city.name

时间:2017-09-16 05:22:28

标签: php mysql codeigniter codeigniter-3

如果连接两个表并显示其他值时出现问题,则会设置表并加载模型并以大写字母开头。

我想要的是匹配jobs.city_id和cities.id并显示cities.city_name

Jobs_model.php

public function get_city(){
$this->db->select('*');
$this->db->from('cities');
$this->db->join('jobs', 'cities.city_name = jobs.city_id');
$this->db->where('jobs.city_id = cities.id');
$query = $this->db->get();
}

Controller.php这样

$data['city_name'] = $this->jobs_model->get_city();

View.php

<?php echo $city_name['city_name'];?>

SQL

CITIES
id
city_name

JOBS
id
city_id 

更新。 sql和拼写错误

6 个答案:

答案 0 :(得分:0)

我给你一个简单的SQL供参考 -
select cities.name from cities, jobs where jobs.city_id = cities.id

答案 1 :(得分:0)

模型更改为

public function get_city(){
$this->db->select('*');
$this->db->from('cities');
$this->db->join('jobs', 'cities.city_id= jobs.city_id');
$this->db->where('jobs.city_id = cities.id');
$query = $this->db->get();
return $query->result_array()
}

答案 2 :(得分:0)

应该是这样的:

join('jobs', 'cities.id = jobs.city_id');

我认为这就是问题所在。

答案 3 :(得分:0)

您正在比较联接查询中的错误字段

var res = [];

function addResults(data) {
    res.push(data);
    console.log('Request # '+res.length);
    if ( res.length >= 2 ) {
        // do stuff
        console.log('both request has done.');
    } else {
        // wait 
    }
}

$.ajax({
    url: 'https://jsonplaceholder.typicode.com/posts',
    success: function (data) {
        addResults(data);
    }
});

$.ajax({
    url: 'https://jsonplaceholder.typicode.com/posts',
    success: function (data) {
        addResults(data);
    }
});

答案 4 :(得分:0)

使用此

$this->db->join('jobs', 'cities.city_id = jobs.city_id');

而不是

$this->db->join('jobs', 'cities.city_name = jobs.city_id');

答案 5 :(得分:0)

  

你还没有在模型函数中返回任何东西

如果需要特定类型的JOIN,可以通过函数的第三个参数指定它。选项包括:左,右,外,内,左外和右外。

下面的这个函数示例只会返回一行,您可能需要使用result_array();请阅读以下链接,了解如何生成结果https://www.codeigniter.com/user_guide/database/results.html

public function get_city(){
    $this->db->select('*');
    $this->db->from('cities');
    $this->db->join('jobs', 'jobs.city_id = cities.id', 'LEFT');
    //$this->db->where('jobs.city_id = cities.id');
    $query = $this->db->get();

    // Note only returns one row
    return $query->row_array();
}

和控制器

$info = $this->jobs_model->get_city();

$data['city_name'] = $info['city_name'];

多重结果

public function get_city(){
    $this->db->select('*');
    $this->db->from('cities');
    $this->db->join('jobs', 'jobs.city_id = cities.id', 'LEFT');
    $query = $this->db->get();

    return $query->result_array();
}

在控制器上

$data['cities'] = $this->jobs_model->get_city();

查看

<?php foreach ($cities as $city) {?>
    <?php echo $city['city_name'];?>
<?php }?>