2
$postModel = new \App\Models\PostModel();
$pager = \Config\Services::pager();
$post = $postModel->orderBy('dteCreatedDate', 'DESC')->findAll();
$data = [
        'post' => $postModel->paginate(2,'post'),
        'pager' => $postModel->pager
     ];

我有上面的代码在我的代码点火器 4 项目中创建一个 simpleLink 分页。此分页有效,但缺少 1 条信息和结果的顺序。

我需要从另一个表中选择一个连接到 PostModel 表的列。如何添加联接和排序依据,$postModel以便我可以获得所需的所有数据并对结果集进行排序。

默认情况下,提供给pagination()模型类的结果是分页的,这就是我想使用这个函数的原因

如何向模型类默认 CRUD 添加连接和排序

4

1 回答 1

1

分页似乎直接作用于模型中声明的表,即在受保护的 $table = 'table_name' 中声明的表。

所以我在想,如果你需要在一个或多个表和其他一些东西上使用 JOIN,那么“一种方法”就是创建一个 VIEW 表。

我对此进行了尝试,并提出了一些工作代码。这是相当微不足道的,但它似乎证明了这一点。

我有两张桌子。(非常松散地基于 Cluedo 和缺乏睡眠)

表格1

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);
}

那么你的 Paginate 方法可能会变成

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 被设置为一个不存在的表。

概括

  1. 创建模型

  2. 将 $table 声明为您的视图名称。

  3. 创建一个创建(或替换)视图的方法。这大约是第一次创建它和后续更新。

  4. 调用创建视图的 Model 方法

  5. 在分页中使用模型。(它现在指向视图)。

这可能不是最好的想法,但它有点适合它想要的工作方式。

我尝试过“标准”方式,但他们不想玩得很好。我还使用了最基本的 CI SQL 功能,如果您愿意,可以使用构建器等。

我希望这能给你一些想法。

于 2020-04-26T13:01:46.490 回答