为什么使用 vsprintf 而不是 sprintf 来格式化查询字符串以传递给 Laravel 的 DB::select 会导致返回非对象?



使用vsprintf而不是sprintf格式化传递给DB::select的查询字符串时遇到问题。我已经通过排除把问题缩小了。起初,我尝试使用sprintf将变量插入字符串中。我使用该字符串作为DB::select:的参数

$query = sprintf("SELECT * FROM test_posts WHERE post_slug = %s;", $post_slug);
$result = DB::select($query);
dd($result);

结果很好。我修改了代码,允许在字符串中插入多个变量:

$table = 'test_posts';
$column = 'post_slug';
$query = vsprintf("SELECT * FROM %s WHERE %s = '%s';", [$table, $column, $identifier_slug]);
$rslt_post = DB::select($query);
//return view('post_viewer', ['arr_post' => $rslt_post] );
echo "<pre>";
print_r($rslt_post);        
dd($rslt_post);

两种代码变体的结果都很好且相同:

Array
(
    [0] => stdClass Object
        (
            [post_ctr] => 2
            [post_slug] => my-first-post
            [posted_by] => J_Rives
            [date_posted] => 2020-02-03 09:03
            [last_edit] => 2020-02-03 16:54
            [post_body] => Test post #2. Ctr = 2, No title.
        )
)
array:1 [▼
  0 => {#250 ▶}
]

我试图返回一个视图,并将结果对象作为参数传递。
return view('post_viewer', ['arr_post' => $rslt_post] );

结果是以下错误消息:

FacadeIgnitionExceptionsViewException
Trying to get property 'posted_by' of non-object (View: C:Users7testproject1.0resourcesviewspost_viewer.blade.php)
http://127.0.0.1:8000/posts/my-first-post

post_viewer.blade.php中引用的行是:
<h4> {{ $arr_post->posted_by }} </h4>

为什么它声称ddprint_r验证为数组对象的变量是"非对象",我试图从中访问名为"title"的"属性"?

无需sprintfvsprintf

$result = DB::select("SELECT * FROM test_posts WHERE post_slug = :slug", ['slug' => $post_slug]);

和全动态

$names = ['test_posts', 'comments'];
$columns = ['post_slug', 'comment_slug'];
foreach($names as $i => $tableName){
     $rslt_post = DB::table($tableName)->where($columns[$i], $identifier_slug);
}

最新更新