如何根据与多对多关系相关联的聊天室(表)create_*at(*field name)字段对EnquiryChat进行排序。聊天室-〉聊天室。
是查询聊天模型的代码。
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use App\Models\User;
use App\Models\EnquiryChatRoom;
class EnquiryChat extends Model
{
use HasFactory;
public function user()
{
return $this->belongsTo(User::class);
}
public function chatRooms(){
return $this->belongsToMany(ChatRoom::class,'enquiry_chat_chatroom','enquiry_chat_id','chatroom_id');
}
}
下面是聊天室模型的代码。
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use App\Models\EnquiryChat;
use App\Models\SaleChat;
use App\Models\Message;
class ChatRoom extends Model
{
use HasFactory;
protected $with = [
'lastMessage'
];
public function enquiryChats(){
return $this->belongsToMany(EnquiryChat::class,'enquiry_chat_chatroom','chatroom_id','enquiry_chat_id');
}
public function messages(){
return $this->hasMany(Message::class,'chatroom_id','id');
}
public function members(){
return $this->belongsToMany(User::class,'chatroom_member','chatroom_id','user_id');
}
}
EnquiryChat和聊天室是多对多的关系。
在下面的函数中,我尝试根据聊天室的created_at列来排序enquiychats,但是这不起作用。
public function index(Request $request)
{
$query = EnquiryChat::query();
$query->withCount('chatRooms')->where('user_id',Auth::user()->id);
$query->with('chatRooms',function($q){
return $q->orderBy('created_at','DESC');
});
if($request->search){
$query->where('cas_no','like','%'.$request->search.'%')->orWhere('product_name','like','%'.$request->search.'%');
}
$chats = $query->get();
if($request->wantsJson()){
return $chats;
}
return Inertia::render('Enquiry/Chats/Index',compact('chats'));
}
上面的查询是对聊天室而不是对EnquiryChats进行排序。是否有一种方法可以根据在创建的聊天室对EnquiryChats进行排序?
1条答案
按热度按时间3okqufwl1#
在查询中尝试: