【问题标题】:How to extract information from stdClass object?如何从 stdClass 对象中提取信息?
【发布时间】:2021-12-25 13:41:21
【问题描述】:

在我的 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]

我做错了什么?

【问题讨论】:

  • 你为什么使用 RAW sql ???使用 Laravel(以及其他)的意义在于使用 Eloquent...阅读entire documentation,这样您就知道您可以做什么以及应该如何使用该框架来做某事...

标签: laravel stdclass


【解决方案1】:

您将数据存储在 $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));

【讨论】:

  • Whelp,解决了它。将来会牢记这一点。谢谢
  • 很高兴它对你有用:)
猜你喜欢
  • 2021-07-04
  • 1970-01-01
  • 2020-06-04
  • 1970-01-01
  • 1970-01-01
  • 2023-03-30
  • 1970-01-01
  • 2020-03-08
  • 1970-01-01
相关资源
最近更新 更多