如何在 Codeigniter 4 中使用多个表
How to use Multiple Tables in Codeigniter 4
到目前为止,我已经使用了 CI 3,我想在一个新模型中(在 CI 4 中)分别处理几个数据库表(没有连接)。
<?php namespace App\Models;
use CodeIgniter\Model;
class MyModel extends Model {
protected $table = 'main_table';
public function getAll($uid = false) {
return $this->where(['hidden' => '0'])
->where(['deleted' => '0'])
->findAll();
}
public function getMainImage($pid) {
return $this->from('another_table')
->where(['pid' => $pid])
->findAll();
}
}
出于某种原因,整个事情似乎没有成功。
有人可以帮助我吗?
您需要再次实例化数据库连接并将第二个 table 分配给函数内的那个变量,如下所示:
public function getMainImage($pid) {
$db = \Config\Database::connect();
$builder = $db->table('secondary_table');
return $builder->where(['pid' => $pid])
->get()->getResult();
}
有关如何使用查询构建器的更多信息,请点击此处:
https://codeigniter.com/user_guide/database/query_builder.html?highlight=query%20builder
到目前为止,我已经使用了 CI 3,我想在一个新模型中(在 CI 4 中)分别处理几个数据库表(没有连接)。
<?php namespace App\Models;
use CodeIgniter\Model;
class MyModel extends Model {
protected $table = 'main_table';
public function getAll($uid = false) {
return $this->where(['hidden' => '0'])
->where(['deleted' => '0'])
->findAll();
}
public function getMainImage($pid) {
return $this->from('another_table')
->where(['pid' => $pid])
->findAll();
}
}
出于某种原因,整个事情似乎没有成功。
有人可以帮助我吗?
您需要再次实例化数据库连接并将第二个 table 分配给函数内的那个变量,如下所示:
public function getMainImage($pid) {
$db = \Config\Database::connect();
$builder = $db->table('secondary_table');
return $builder->where(['pid' => $pid])
->get()->getResult();
}
有关如何使用查询构建器的更多信息,请点击此处: https://codeigniter.com/user_guide/database/query_builder.html?highlight=query%20builder