Joomla:使用JDatabaseQuery来表示插入..选择查询?

Sea*_*ean 0 php mysql joomla

因此,我需要运行一个long(ish)查询,根据数据库中其他位置的另一行的值,将新行插入表中.这是在Joomla 3.1.5中运行的

通常,您可以使用MySql的INSERT .. SELECT语法轻松完成此操作,但我正在寻找一种方法来接近Joomla的查询构建器,例如:

<?php

// ...

// Base Tables & Columns.

$my_table = '#__my_table';

$columns = array('column_one', 'column_two');

// Set up the database and query.

$db = JFactory::getDBO();

$query = $db->getQuery(true);

// Escape / quote the table name.
$my_table = $db->quoteName($my_table);

// Escape all columns.
$cols = array_map(array($db, 'quoteName'), $cols);

$query
    ->insert($my_table)
    ->columns($columns)
    // E.g. ->select( ... )->from( ... ) ...

$db->setQuery($query);

$result = $db->query();

// ...

?>
Run Code Online (Sandbox Code Playgroud)

当然,示例注释不起作用,但我想知道是否有一种方法可以让我执行类似的操作(无需在别处运行单独的查询).

当然,如果无法执行此类查询,我可以直接使用原始查询字符串.

Eli*_*lin 5

许多JDatabaseQuery方法的docblock包括以下语句

 * Note that you must not mix insert, update, delete and select method calls when building a query.
Run Code Online (Sandbox Code Playgroud)

这是因为...过度简化,但作为一个例子,我们如何知道在构建查询时将哪个列列表(或哪个where子句等)放在哪里.

但是有一些方法可以通过稍微复杂的方式构建查询来解决这个限制(这是公平的,因为它是一个更复杂的查询).所以举个例子

$db = JFactory::getDBO();

$queryselect = $db->getQuery(true);
$queryselect->select($db->quoteName(array('id','title','alias')))
    ->from($db->quoteName('#__content'));
$selectString = $queryselect->__toString();


$queryInsert = $db->getQuery(true);
$queryInsert->columns($db->quoteName(array('id','title','alias')))
->insert($db->quotename('#__newtable'));

$db->setQuery($queryInsert . $selectString);
$db->execute();
Run Code Online (Sandbox Code Playgroud)