【问题标题】:Get all the related data from tables in the same WordPress DB从同一个 WordPress 数据库中的表中获取所有相关数据
【发布时间】:2018-08-24 04:10:46
【问题描述】:

我在安装了 WordPress 的数据库中有 2 个自定义表,两个表之间有 one-to-many 关系。

这是两张表:

                     posts table
_________________________________________________________________
| id | title | content | category_id | post_order  | post_active |                                        
|____|_______|_________|_____________|_____________|_____________|
| 1  | test1 | testing |     1       |       0     |      1      |
| 2  | test2 | testing |     1       |       1     |      1      |
| 3  | test3 | testing |     2       |       2     |      0      |
| .  | ..... | ....... |     .       |       .     |      .      |
|____|_______|_________|_____________|_____________|_____________|


       categories table
_____________________________________
| c_id | c_name | c_order | c_active |                                       
|______|________|_________|__________|
|   1  |  cat1  |    0    |    1     |
|   2  |  cat2  |    1    |    1     |      
|   3  |  cat3  |    2    |    0     |  
| .    | .....  | ....... |    .     |      
|______|________|_________|__________|

如您所见,每个帖子都有一个使用posts 表中的category_id 列和categories 表中的c_id 列的类别。

我想显示来自posts 表的所有数据以及相关类别。

这就是我尝试过的:

global $wpdb;

$results = $wpdb->get_results("SELECT b.c_name, a.id, TRIM(a.title) AS title, a.content
FROM posts a
INNER JOIN categories b ON a.category_id = b.c_id
WHERE a.post_active = '1' AND b.c_active = '1'
ORDER BY b.c_order, a.post_order", OBJECT_K );

print_r($results);

但我只收到每个活跃category 的第一个帖子:

Array
(
    [cat1] => stdClass Object
        (
            [c_name] => cat1
            [id] => 1
            [title] => test1
            [content] => testing
        ) 

    [cat2] => stdClass Object
        (
            [category_name] => cat2
            [id] => 3
            [title] => test3
            [content] => testing
        ) 
)

出了什么问题以及如何解决?

【问题讨论】:

    标签: php mysql sql wordpress object


    【解决方案1】:

    尝试左连接然后检查:

    全局 $wpdb;

                $results = $wpdb->get_results("SELECT b.c_name, a.id, TRIM(a.title) AS title, a.content
                FROM posts a
                LEFT JOIN categories b ON a.category_id = b.c_id
                WHERE a.post_active = '1' AND b.c_active = '1'
                ORDER BY b.c_order, a.post_order", OBJECT_K );
    
                print_r($results);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-05-24
      • 2012-12-31
      • 2020-11-02
      • 2019-04-18
      • 2013-09-02
      • 1970-01-01
      • 2019-07-01
      • 1970-01-01
      相关资源
      最近更新 更多