| 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980 |
- <?php
- namespace App\Http\Controllers\V1;
- use App\Models\Msg;
- use App\Models\MsgRead;
- use App\Models\Product;
- use Illuminate\Http\Request;
- class MsgController extends Controller
- {
- public function __construct()
- {
- $this->user = auth('api')->user();
- $this->userId = $this->user ? $this->user->id : 0;
- //如果用户被删除,会自动退出登录
- if (!empty($this->user->deleted_at)) {
- $this->user->online = 0;
- $this->user->save();
- auth('api')->logout();
- }
- }
- /**
- * @return void
- * 消息列表
- */
- public function msgList(Request $request){
- $limit = $request->get('limit',10);
- $list = Msg::query()->with('user:id,name,avatar')->withCount(['read' => function($item){
- $item->where('user_id',$this->userId);
- }])->where('to_user_id',$this->userId)
- ->orWhere('to_user_id',0)
- ->orderByDesc("id")
- ->paginate($limit);
- foreach ($list as $v){
- if($v){
- $v['productList'] = Product::select('id','image')->whereIn('id',explode(',',$v['product_id']))->get();
- $v['is_read'] = $v['read_count'];
- }
- }
- return $this->success($this->page($list));
- }
- /**
- * @param Request $request
- * @return void
- * 消息详情
- */
- public function msgDetail(Request $request){
- $id = $request->get('id');
- if(!$id){
- return $this->error("缺少参数ID!");
- }
- $msg = Msg::query()->with('user:id,name,avatar')->where('id',$id)->first();
- $MsgRead = MsgRead::query()->where('user_id',$this->userId)->where('msg_id',$msg['id'])->count();
- if(!$MsgRead){
- $data =[
- 'user_id'=>$this->userId,
- 'msg_id'=>$msg['id']
- ];
- MsgRead::query()->create($data); // 已读
- }
- return $this->success($msg);
- }
- public function getNewMsgState(){
- $read = Msg::join('msg_read','msg.id','=','msg_read.msg_id')->count();
- $msg = Msg::where('to_user_id',$this->userId)->count();
- return $this->success([
- 'isNewMsg' => ($msg - $read) > 0 ? 1 : 0
- ]);
- }
- }
|