如何从stdClass对象中提取信息



在Mailable的build函数中,我从数据库中提取信息,如下所示:

$this->data = DB::select('select * from newsletter_mails order by id desc limit 1')[0];
Log::info(print_r($this->data, true));
$this->subject = $this->data->subject;
$this->content = $this->data->content;
Log::info(print_r($this->subject, true));
Log::info(print_r($this->content, true));

生成日志:

[2021-11-13 15:49:41] production.INFO: stdClass Object
(
[id] => 2
[from] => test@test.com
[subject] => testSubject
[content] => testMessage
[file] => 
[created_at] => 2021-11-13 15:49:10
[updated_at] => 2021-11-13 15:49:10
)

[2021-11-13 15:49:41] production.INFO: testSubject  
[2021-11-13 15:49:41] production.INFO: testMessage  

正如您所看到的,data变量是stdClass Object,并且信息被正确提取。但现在我想得到from值:

$this->from = $this->data->from;
Log::info(print_r($this->from, true));

这会在日志中输出两件事。首先是$this->form:的正确输出

[2021-11-13 15:55:25] production.INFO: test@test.com  

但也有一个错误:

[2021-11-13 15:55:25] production.ERROR: Cannot access offset of type string on string {"userId":1,"exception":"[object] (TypeError(code: 0): Cannot access offset of type string on string at C:\Users\Artur\PhpstormProjects\stuttard.de\vendor\laravel\framework\src\Illuminate\Mail\Mailable.php:360)
[stacktrace]

我做错了什么?

您将数据存储在$this->data属性,并覆盖Mailable类的所有其他属性。

您应该将数据库中的数据存储在本地变量中,如下所示:

$data = DB::select('select * from newsletter_mails order by id desc limit 1')[0];
$from = $data->from;
Log::info(print_r($from, true));

最新更新