$postModel = new \App\Models\PostModel();
$pager = \Config\Services::pager();
$post = $postModel->orderBy('dteCreatedDate', 'DESC')->findAll();
$data = [
'post' => $postModel->paginate(2,'post'),
'pager' => $postModel->pager
];
我有上面的代码在我的 code igniter 4 项目中创建一个 simpleLink 分页。此分页有效,但缺少 1 个信息和对结果的排序。
我需要从连接到 PostModel 中的表的另一个表中选择一列。
如何向 $postModel
添加连接和排序依据,以便我可以获得我需要的所有数据并对结果集进行排序。
被提供给模型类的 pagination()
的结果默认是分页的,这就是我想使用这个函数的原因
如何向模型类默认 CRUD 添加连接和排序
最佳答案
分页似乎直接作用于模型中声明的表,即在 protected $table = 'table_name' 中声明的内容。
所以我在想,如果您需要在一个或多个表和其他一些东西上使用 JOIN,解决这个问题的“一种方法”是创建一个 VIEW 表。
我试了一下这个并想出了一些工作代码。 这相当微不足道,但似乎证明了这一点。
我有两张 table 。 (非常松散地基于 Cluedo 和 sleep 不足)
表一
table_1
id,
name,
type
with inserted data of
1, Fred, Baker
2, Sam , Candle Stick Maker
表2
table_2
id,
place
with inserted data of
1, Laundry
2, Bathroom
在我的 PostModel 中
protected $table = 'table_view';
/**
* Only need to create the View so the pagination can access it via
* $this->table (protected $table = 'table_view')
*/
public function create_view() {
$sql = "CREATE OR REPLACE VIEW table_view AS ";
// Whatever your SQL needs to be goes here
$sql .= "SELECT t1.name, t1.type, t2.place FROM table_2 t2
JOIN table_1 t1 on t1.id = t2.table_1_id";
echo $sql;
$query = $this->db->query($sql);
}
然后你的分页方法可以变成
public function index() {
$postModel = new \App\Models\PostModel();
$postModel->create_view();
$pager = \Config\Services::pager();
$data = [
'posts' => $postModel->paginate(2),
'pager' => $postModel->pager
];
echo view('users_view', $data);
}
我的观点是
<h2> The results</h2>
<?php
echo '<pre>';
echo 'LINE: ' . __LINE__ . ' Module ' . __CLASS__ . '<br>';
var_dump($posts);
echo '</pre>';
?>
<table>
<?php foreach ($posts as $post): ?>
<tr>
<td><?= $post['name']; ?></td>
<td><?= $post['type']; ?></td>
<td><?= $post['place']; ?></td>
</tr>
<?php endforeach; ?>
</table>
它给出了(我没有包含分页但我测试过)的输出
CREATE OR REPLACE VIEW table_view AS SELECT t1.name, t1.type, t2.place FROM table_2 t2 JOIN table_1 t1 on t1.id = t2.table_1_id
The results
LINE: 10 Module
array(2) {
[0]=>
array(3) {
["name"]=>
string(4) "Fred"
["type"]=>
string(5) "Baker"
["place"]=>
string(7) "Laundry"
}
[1]=>
array(3) {
["name"]=>
string(3) "Sam"
["type"]=>
string(18) "Candle Stick Maker"
["place"]=>
string(8) "Bathroom"
}
}
Fred Baker Laundry
Sam Candle Stick Maker Bathroom
“看起来”表名,在本例中是一个不存在的表(直到它被创建)不会扰乱模型的 $table 被设置为一个不存在的表。
总结
创建模型
将 $table 声明为您的 View 名称。
创建一个创建(或替换) View 的方法。 这大约是第一次创建它和随后的更新。
调用创建 View 的Model方法
在您的分页中使用该模型。 (它现在指向 View )。
这可能不是最好的想法,但它在某种程度上使其符合它想要的工作方式。
我已经尝试过“标准”方式,但他们不想玩得很好。 我还使用了最基本的 CI SQL 功能,您可以根据需要使用构建器等。
我希望这能给你一些想法。
关于class - Codeigniter 4 使用模型类的默认分页没有顺序和加入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61438491/