douzhao9608 2010-12-10 09:19
浏览 33
已采纳

如何从CodeIgniter中的一对多关系中进行选择?

I have a number of tables that I'm trying to access in CodeIgniter, and one of them is basically a collection of foreign keys from the other tables, most of which are only two fields: a unique id and a name. The "campaigns" table, let's call it, pulls data from other tables in the form of those tables' ids (because the names may not be unique).

Now what I want to do is display the "campaigns" data in human-readable form, meaning, showing the foreign names, not the ids. I think this is called a 'join,' but I'm not 100% certain on that. I checked MySql's page and they say that that isn't actually what foreign keys are for, but I thought that you needed foreign keys for a join, so I'm really just more confused now.

Do I really use joins and foreign keys for this? Thanks in advance.

  • 写回答

1条回答 默认 最新

  • douyue8685 2010-12-10 12:15
    关注

    The foreign key provides a link to another record in the same or another table (usually the latter). A join uses common data in two tables (sometimes the same table) to provide a link between them.

    If you have two tables that you want to join and the only common factor between those two tables is in a third table (the one with all the foreign keys) you will need to perform 2 joins.

    Example

    SELECT *.table1, *.table2 FROM table1
    LEFT JOIN foreign_key_table ON foreign_key_table.id1 = table1.id
    LEFT JOIN table2 ON foreign_key_table.id2 = table2.id
    WHERE.....
    

    In Codeignter:

    $this->db->select('*.table1, *.table2');
    $this->db->from('table1');
    $this->db->join('foreign_key_table', 'foreign_key_table.id1 = table1.id');
    $this->db->join('table2', 'foreign_key_table.id2 = table2.id');
    $this->db->where('...');
    

    You can find all the information you need here - http://codeigniter.com/user_guide/database/active_record.html

    Hope this helps.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 完全没有学习过GAN,看了CSDN的一篇文章,里面有代码但是完全不知道如何操作
  • ¥15 使用ue5插件narrative时如何切换关卡也保存叙事任务记录
  • ¥20 软件测试决策法疑问求解答
  • ¥15 win11 23H2删除推荐的项目,支持注册表等
  • ¥15 matlab 用yalmip搭建模型,cplex求解,线性化处理的方法
  • ¥15 qt6.6.3 基于百度云的语音识别 不会改
  • ¥15 关于#目标检测#的问题:大概就是类似后台自动检测某下架商品的库存,在他监测到该商品上架并且可以购买的瞬间点击立即购买下单
  • ¥15 神经网络怎么把隐含层变量融合到损失函数中?
  • ¥15 lingo18勾选global solver求解使用的算法
  • ¥15 全部备份安卓app数据包括密码,可以复制到另一手机上运行