我收到错误消息“模型[App \ Posts]没有查询结果。”,但是模型确实返回了结果。我正在尝试使用pusher发出有关新帖子的事件。
$post = \App\Posts::find(1);
if($post) {
event(new \App\Events\NewPost($post));
}
事件:
class NewPost implements ShouldBroadcastNow
{
use Dispatchable, InteractsWithSockets, SerializesModels;
private $post;
/**
* Create a new event instance.
*
* @return void
*/
public function __construct($post)
{
$this->post = $post;
}
/**
* Get the channels the event should broadcast on.
*
* @return \Illuminate\Broadcasting\Channel|array
*/
public function broadcastOn()
{
return new Channel('messages');
}
public function broadcastWith() {
return [
'id' => $this->post->id
];
}
}
答案 0 :(得分:0)
数据库中的自动增量ID始终从1
开始而不是零,因此ID为Post
的{{1}}将永远不存在。然后,Eloquent找不到ID为0
的记录。
答案 1 :(得分:0)
我找到了解决方案。该错误是因为$ post已由SerializesModels序列化。
将use Dispatchable, InteractsWithSockets, SerializesModels;
更改为:
use Dispatchable, InteractsWithSockets;
帮助了。
答案 2 :(得分:0)
要建立在SerializesModels
上的发现基础上,这是因为trait强制事件期望其为JSON或Array。要在不删除特征的情况下对其进行排序,可以在模型上调用->toArray()
。
像这样:
event(new NewPost($post->toArray()));
更多内容是here