Laravel 5 如何使用laravel中的方法关系获取中的最后一行?
我正在尝试使用laravel构建一个聊天应用程序,我有两个表,一个用于对话,另一个用于消息,我希望每个对话都包含最后一条消息。这是我尝试的查询:Laravel 5 如何使用laravel中的方法关系获取中的最后一行?,laravel-5,eloquent,Laravel 5,Eloquent,我正在尝试使用laravel构建一个聊天应用程序,我有两个表,一个用于对话,另一个用于消息,我希望每个对话都包含最后一条消息。这是我尝试的查询: $allConvs = Conversation::with(['messages' => function ($query) { $query->latest()->first(); }]) ->get(); 但它只为第一次对话返回最后一条消息,其他对话返回null。还有别的办法吗? 这就是我的关系 Conver
$allConvs = Conversation::with(['messages' => function ($query) {
$query->latest()->first();
}])
->get();
但它只为第一次对话返回最后一条消息,其他对话返回null。还有别的办法吗?
这就是我的关系
Conversation.php
public function messages(){
return $this->hasMany('App\Message', 'conversation_id','id')->latest();}
public function conversation()
{
return $this->belongsTo('App\Conversation' ,'id', 'conversation_id');
}
Message.php
public function messages(){
return $this->hasMany('App\Message', 'conversation_id','id')->latest();}
public function conversation()
{
return $this->belongsTo('App\Conversation' ,'id', 'conversation_id');
}
您可以使用
HasOne
关系:
public函数latestMessage(){
返回$this->hasOne(Message::class)->latest();
}
$allConvs=Conversation::with('latestMessage')->get();
这仍将在后台获取所有消息,但仅显示每个对话的最新消息。您可以使用
HasOne
关系:
public函数latestMessage(){
返回$this->hasOne(Message::class)->latest();
}
$allConvs=Conversation::with('latestMessage')->get();
这仍将在后台获取所有消息,但每次对话仅显示最新消息。效果非常好!我不知道有这种方法。效果很好!我不知道有这种方法。