简体   繁体   English

Codeigniter的活动记录中的mysql查询

[英]mysql query in codeigniter's active record

I am running this query, 我正在运行此查询,

$this->db->select('news.news_id, news.title, news.article, news.date_posted, news_assets.news_assets_id, news_assets.url')
        ->from('news_assets')
        ->join('news', 'news_assets.news_news_id = news.news_id', 'left')
        ->order_by('news.date_posted', 'DESC');

        $query = $this->db->get();

        return $query->row_array();

Now this query returns a news article, and it should return any attributed assets from the news assets table, the news assets table has 1:n relationship with news so a news article may have an infinite amount of assets but an asset with only ever have 1 news article. 现在,此查询返回新闻文章,它应该返回新闻资产表中的所有归因资产,新闻资产表与新闻具有1:n的关系,因此新闻文章可能具有无限量的资产,但只有1条新闻文章。

My question is that when I run this query only one asset for a news article is returned, why would this be? 我的问题是,当我运行此查询时,仅返回新闻文章的一项资产,为什么会这样?

也许您确实在资产表中有一行,但是如果没有,我想您的JOIN是错误的,也许您是在向左转而向右转,还是相反

Try below Query. 请尝试以下查询。

    $this->db->select('news.news_id, news.title, news.article, news.date_posted, news_assets.news_assets_id, news_assets.url');
    $this->db->from('news_assets');
    $this->db->join('news', 'news.news_id=news_assets.news_news_id', 'left');
    $this->db->order_by('news.date_posted', 'DESC');

First of all, as for my thoughts, you should select news and join news_assets because your assets belongs to one news article as I understand. 首先,就我的想法而言,您应该选择新闻并加入news_assets因为据我所知,您的资产属于一篇新闻文章。

Also you have $query->row_array(); 你也有$query->row_array(); which returns just one row, but if you have 1+ rows you should use, according to this : 它仅返回一行,但是如果您有1+行,则应按照以下步骤使用

foreach ($query->result_array() as $row) {
   echo $row['title'];
   echo $row['name'];
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM