<?php

namespace App\Models\Goodnight;

use Illuminate\Database\Eloquent\Model;
use App\Models\User\UserModel;

/**
 * App\Models\Goodnight\RoomMemberModel
 *
 * @property int $id
 * @property int $uid
 * @property int $room_id 房间ID
 * @property string $day1_voice
 * @property string $day2_voice
 * @property string $day3_voice
 * @property \Illuminate\Support\Carbon $created_at
 * @property \Illuminate\Support\Carbon $updated_at
 * @property-read \App\Models\User\UserModel $user
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\Goodnight\RoomMemberModel newModelQuery()
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\Goodnight\RoomMemberModel newQuery()
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\Goodnight\RoomMemberModel query()
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\Goodnight\RoomMemberModel whereCreatedAt($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\Goodnight\RoomMemberModel whereDay1Voice($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\Goodnight\RoomMemberModel whereDay2Voice($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\Goodnight\RoomMemberModel whereDay3Voice($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\Goodnight\RoomMemberModel whereId($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\Goodnight\RoomMemberModel whereRoomId($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\Goodnight\RoomMemberModel whereUid($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\Goodnight\RoomMemberModel whereUpdatedAt($value)
 * @mixin \Eloquent
 */
class RoomMemberModel extends Model
{
    //
    protected $table = 'kdgx_goodnight_room_members';

    protected $dateFormat = "U";

    protected $fillable = ['uid', 'room_id', 'day1_voice', 'day2_voice', 'day3_voice'];


    public function user()
    {
        return $this->hasOne(UserModel::class, 'uid', 'uid')->select('nickname', 'headimgurl', 'sex');
    }


    /**
     * 获取两个人的共同房间
     * @param int $uid
     * @param int $friend_uid
     * @return array
     */
    public function friendRooms($uid, $friend_uid)
    {
        $rooms = \DB::select("SELECT room_id
          FROM(
        SELECT `room_id`
          FROM `kdgx_goodnight_room_members`
         WHERE `uid`= ?
         UNION ALL
        SELECT `room_id`
          FROM `kdgx_goodnight_room_members`
         WHERE `uid`= ?) as t
         GROUP BY room_id
        HAVING COUNT(*)>= 2", [$uid, $friend_uid]);
        $array = [];
        $rooms = array_map(function ($value) use (&$array) {
            array_push($array, $value->room_id);
        }, $rooms);
        return $array;
    }
}
