gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 00:46:31 27 4
gpt4 key购买 nike

所以我需要运行一个很长的查询来根据数据库中其他地方的另一行的值将新行插入到表中。这是在 Joomla 3.1.5 中运行

通常,您可以使用 MySql's INSERT .. SELECT syntax轻松做到这一点,但我正在寻找一种方法来接近 Joomla's query builder , 例子:

<?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();

// ...

?>

当然,示例评论不会起作用,但我想知道是否有一种方法可以让我执行类似的操作(无需在其他地方运行单独的查询)。

当然,如果没有办法执行这种类型的查询,我可以直接使用原始查询字符串。

最佳答案

许多JDatabaseQuery 方法的文档 block 包括以下语句

 * Note that you must not mix insert, update, delete and select method calls when building a query.

这是因为...过度简化,但作为示例,我们如何知道在构建查询时将哪个列列表(或哪个 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();

关于php - Joomla:使用 JDatabaseQuery 来表示插入 .. 选择查询?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21455234/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com