我有一个原始的SQL查询代码,我想使用laravel中的laravel查询构建器运行:
$q = "SELECT * FROM wp_posts WHERE post_parent = ? ORDER BY ? ? LIMIT ?, ?";
$values = ['40','post_status', "ASC" ,'1','10'];
$q = $db->connection()->select($q,$values);
此查询将抛出错误消息
SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error
in your SQL syntax; check the manual that corresponds to your MySQL server
version for the right syntax to use near '? LIMIT ?, ?' at line 1 (SQL:
SELECT * FROM wp_posts WHERE post_parent = `40` ORDER BY `post_status` ASC LIMIT 1, 10)
现在,当我从错误输出中复制查询并将其粘贴到phpmyadmin sql runner中时,它将运行时没有任何错误。
任何想法?
答案 0 :(得分:0)
可能是post_parent不是字符串而且不需要背景
$q = "SELECT * FROM wp_posts WHERE post_parent = ? ORDER BY ? ? LIMIT ?, ?";
$values = [ 40,'post_status', "ASC" ,'1','10'];
答案 1 :(得分:0)
你可以写
$q = "SELECT * FROM wp_posts WHERE post_parent = ? ORDER BY ? ? LIMIT ?, ?";
$values = [ 40,'post_status', "ASC" , 1, 10];
希望这将解决您的问题
答案 2 :(得分:0)
如果您想使用查询构建器执行此操作,这应该可以。
$posts = DB::table('wp_posts')->where('post_parent', 40)->orderBy('post_status', 'ASC')->take(10)->get();
Laravel会自动将值绑定到PDO。
答案 3 :(得分:0)
似乎查询构建器不允许将SQL命令放入绑定变量中,当我从其工作的绑定变量中删除“ASC”时:
$q = "SELECT * FROM wp_posts WHERE post_parent = ? ORDER BY ? ASC LIMIT ?, ?";
$values = [40,'post_status', 1,10];
$q = $db->connection()->select($q,$values);