0

在终端上,在 mysql 中,运行以下查询会给出此结果

mysql> SELECT DISTINCT(city) FROM outlets_data;
+-----------+
| city      |
+-----------+
| Paris     |
| New York  |
| Kolkata   |
| Moscow    |
| Mumbai    |
| Hyderabad |
| Delhi     |
| Chennai   |
+-----------+
8 rows in set (0.00 sec)

我想将这些城市的名称以数组的形式存储在 codeigniter 4 模型类文件中。

模型/DashboardModels.php

<?php

namespace App\Models;

use CodeIgniter\Model;

class DashboardModel extends Model
{
    protected $table      = 'outlets_data';
    protected $primaryKey = 'shop_id';

    public function not_defined_yet()
    {
        $city_names = $this->select('city')->distinct(); // This should be equivalent to "SELECT DISTINCT(city) FROM outlets_data";
        
        return $city_names;
    }
}

控制器/Home.php

<?php

namespace App\Controllers;

use App\Models\DashboardModel;

use CodeIgniter\Model;

class Home extends BaseController
{
    public function index()
    {
        $model = new DashboardModel();
        $data['undefined'] = $model->not_defined_yet();

        echo view('dashboard', $data);
    }
}

视图/仪表板.php

 <?php echo "<pre>";  print_r($undefined); echo "</pre>"; ?>

我希望在输出数组中获得城市的名称,但我将整个数据库作为关联数组。

4

1 回答 1

1

你的功能应该是:

public function not_defined_yet()
{
    $city_names = $this->select('city')->distinct(); // This should be equivalent to "SELECT DISTINCT(city) FROM outlets_data";
    
    return $this;
}

那么你的功能是

$data['undefined'] = $model->not_defined_yet()->findAll();

其他方法是加载数据库对象的新实例。

public function not_defined_yet()
{

    $db         = \Config\Database::connect();
    $builder    = $db->table('outlets_data');
    $city_names = $builder->select('city')->distinct(); 
    
    return $city_names->resultArray();
}

您甚至可以一起删除该功能,并在您的控制器中执行以下操作:

$data['undefined'] = $model->select('city')->distinct()->findAll();

这将得到相同的确切结果。

于 2021-02-18T16:42:28.593 回答