【问题标题】:Laravel 5.4 Eloquent not returning object, it returned as arrayLaravel 5.4 Eloquent 不返回对象,它作为数组返回
【发布时间】:2018-01-18 17:47:07
【问题描述】:

我正在尝试使用 eloquent 查询从模型中获取数据。它没有返回我一个对象,而是返回一个数组。代码如下所示。

    public function showConversation($id,$cid){
    $conversation=conversation::where('from',$id)->orWhere('to',$id)->orderBy('created_at','desc')->get()->all();
    $message=message::where('conversation_id',$cid)->orderBy('created_at','desc')->get();        
    $key='conversation';
    dd($message->id);
    return view('inbox')->with('conversation',$conversation)->with('message',$message)->with('key',$key);
}

通过 dd $message 不能作为 $message->id 访问,它显示错误试图获取非对象的属性。但是当我们使用 $message[0]->id 时,它是可以访问的。我们想要它的对象。有人可以帮忙吗?

【问题讨论】:

  • 在控制器中将 $message 重命名为 $messages 以使用复数形式。像foreach ($messages as $message) 这样的视图中的 foreach 应该可以工作,除非发生了一些奇怪的事情。

标签: php database laravel-5.4


【解决方案1】:

您将数据作为数组检索。如果您希望只收到一条消息作为结果,您应该尝试以下代码:

public function showConversation($id,$cid){ $conversation=conversation::where('from',$id)->orWhere('to',$id)->orderBy('created_at','desc')->get()->all(); $message=message::where('conversation_id',$cid)->orderBy('created_at','desc')->first();
$key='conversation'; dd($message->id); return view('inbox')->with('conversation',$conversation)->with('message',$message)->with('key',$key); }

简而言之: 使用->first() 而不是->get()

【讨论】:

  • 我们想要获取所有消息
  • 我们怎样才能得到一个包含所有消息的对象到一个对象中?
  • 那难怪是数组?您正在检索多条消息,因此它作为 Eloquent 对象数组返回。对象包含在数组中。我认为不可能检索对象中的数据。
  • 我们如何在 foreach 循环中使用视图中的数组来执行此操作,如 message->messagetext。
  • 您可能正在使用刀片模板,所以它会类似于以下内容:@foreach ($messages as $message) <p>This is the message body: {{ $message->messagetext}}</p> @endforeach 希望这会有所帮助。 StackOverflow 上的评论不能很好地缩进代码:P.
猜你喜欢
  • 1970-01-01
  • 2021-06-03
  • 1970-01-01
  • 2016-02-18
  • 2015-01-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多