阅读(3555) (1)

Joomla 从多单表查询数据

2023-03-10 11:13:26 更新

如何使用joomla从数据库中查询数据

从多单表中查询数据

下面是使用JDatabaseQuery类的join方法,我们可以从多个表中查询数据。iner方法有两个参数,一个指定链接的类型(inner,outer,left,right),另外一个是链接的条件。inner中,我们可以使用所有原生的SQL关键词,比如AS对表进行别名,ON来指定关联。代码如下:

// 得到数据库链接
$db = JFactory::getDbo();
 
// 创建新的查询对象
$query =$db->getQuery(true);
 
// 查询内容
$query
    ->select(array('a.*','b.username','b.name'))
    ->from($db->quoteName('#__content','a'))
    ->join('INNER',$db->quoteName('#__users','b') .' ON ' .$db->quoteName('a.created_by') .' = ' .$db->quoteName('b.id'))
    ->where($db->quoteName('b.username') .' LIKE ' .$db->quote('a%'))
    ->order($db->quoteName('a.created') .' DESC');
 
// 设置查询
$db->setQuery($query);
 
// 获得结果
$results =$db->loadObjectList();

上面的join方法使我们能够查询#__content表和#__users表.为了方便使用,对inner的4种类型进行了封装,分别提供了4个方法:

  • innerJoin()
  • leftJoin()
  • rightJoin()
  • outerJoin()

我们可以使用多个join方法来查询两个或者两个以上的表。代码如下:

$query
    ->select(array('a.*','b.username','b.name','c.*','d.*'))
    ->from($db->quoteName('#__content','a'))
    ->join('INNER',$db->quoteName('#__users','b') .' ON ' .$db->quoteName('a.created_by') .' = ' .$db->quoteName('b.id'))
    ->join('LEFT',$db->quoteName('#__user_profiles','c') .' ON ' .$db->quoteName('b.id') .' = ' .$db->quoteName('c.user_id'))
    ->join('RIGHT',$db->quoteName('#__categories','d') .' ON ' .$db->quoteName('a.catid') .' = ' .$db->quoteName('d.id'))
    ->where($db->quoteName('b.username') .' LIKE ' .$db->quote('a%'))
    ->order($db->quoteName('a.created') .' DESC');

 有时候,为了避免字段名的冲突,我们需要用AS对表进行别名或者直接使用$db->quoteName的第二个参数对表进行别名。代码如下:

$query
    ->select('a.*')
    ->select($db->quoteName('b.username','username'))
    ->select($db->quoteName('b.name','name'))
    ->from($db->quoteName('#__content','a'))
    ->join('INNER',$db->quoteName('#__users','b') .' ON ' .$db->quoteName('a.created_by') .' = ' .$db->quoteName('b.id'))
    ->where($db->quoteName('b.username') .' LIKE ' .$db->quote('a%'))
    ->order($db->quoteName('a.created') .' DESC');