【问题标题】:Yii select with multiple tables with conditionsYii 选择带有条件的多个表
【发布时间】:2014-06-11 13:46:59
【问题描述】:

我是 yii 的新手,如何使用 yii 进行查询?

查询是:

从 table1、table2、table3 中选择 table1.userid 作为 userid,table2.name 作为用户名,table3.name 作为 tourname,其中 table1.userid=table2.id 和 table1.tid=table3.id order by table1.weight, table1.result

谢谢, 莱斯利

【问题讨论】:

  • 你不想使用 activerecords 或者只想知道如何在 Yii 中执行这种格式的查询?
  • Yii::app()->db->createCommand("select table1.userid as userid, table2.name as username, table3.name as tourname from table1, table2, table3 where table1.userid=table2.id and table1.tid=table3.id order by table1.weight, table1.result")->queryAll()。如果没有 AR。

标签: php yii


【解决方案1】:

你也可以使用 Yii 的Query Builder

看起来像这样:

$results = Yii::app()->db->createCommand()
    ->select('t1.userid as userid,t2.name as username,t3.name as tourname')
    ->from('table1 t1')
    ->join('table2 t2','on'=> 't1.userid=t2.id') // could be ->leftJoin() as well
    ->join('table3 t3,'on'=>'t1.tid=t3.id')
    ->order('t1.weight,t1,result')
    ->queryAll()

请注意,我使用连接而不是在 where 子句中命名两个表。这是在 SQL 中执行关系查询的两种不同方式。您的方法称为隐式连接,而我的方法称为显式连接

我曾经编写隐式连接,但现在我主要使用显式连接,因为它们更易于维护、读取和根据需要进行更改。

更多关于CDBCommand的信息在这里。

【讨论】:

    【解决方案2】:

    Ineersa 是正确的。这个问题最直接的答案是:

    Yii::app()->db->createCommand("select table1.userid as userid, table2.name as username, table3.name as tourname from table1, table2, table3 where table1.userid=table2.id and table1.tid=table3.id order by table1.weight, table1.result")->queryAll();
    

    但我认为你应该利用 Yii 建立关系的能力,以便更好地访问这些信息。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-07-17
      • 2010-12-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-05-17
      相关资源
      最近更新 更多