在终端上,在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 models类文件中的数组中。
模型/DashboardModels.php
<?php
namespace AppModels;
use CodeIgniterModel;
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
namespace AppControllers;
use AppModelsDashboardModel;
use CodeIgniterModel;
class Home extends BaseController
{
public function index()
{
$model = new DashboardModel();
$data['undefined'] = $model->not_defined_yet();
echo view('dashboard', $data);
}
}
视图/Dashboard.php
<?php echo "<pre>"; print_r($undefined); echo "</pre>"; ?>
我期望在输出数组中得到城市的名称,但我得到整个数据库作为关联数组。
你的函数应该是:
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 = ConfigDatabase::connect();
$builder = $db->table('outlets_data');
$city_names = $builder->select('city')->distinct();
return $city_names->resultArray();
}
你甚至可以删除所有的函数,在你的控制器中这样做:
$data['undefined'] = $model->select('city')->distinct()->findAll();
这将得到相同的结果。