Laravel по-русски

Русское сообщество разработки на PHP-фреймворке Laravel.

Ты не вошёл. Вход тут.

#1 24.05.2019 20:29:41

Как получить количество сообщений из другой таблицы в orm запросе?

Как получить количество сообщений из другой таблицы в orm запросе?

     $messages = ChatMessage::where('user_id', Auth::id())
            ->orderBy('created_at', 'desc')
            ->select(['chat_id'])
            ->distinct()
            ->with('chat.last_message.user_fields')
            ->with('chat.last_message.user_session')
            ->get();
  <?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class ChatMessage extends Model
{
    protected $fillable = ['chat_id','user_id', 'text'];

    public function user_fields()
    {
        return $this->hasMany('App\Models\UserFieldsValues','user_id','user_id')
            ->where('fields_id',35)
            ->orWhere('fields_id',36);
    }

    public function user_session()
    {
        return $this->hasOne('App\Models\Session','user_id','user_id')
            ->orderBy('last_activity', 'desc')
            ->where('last_activity','>', time()-5*60)
            ->select(['id','last_activity', 'user_id']);
    }

    public function chat()
    {
        return $this->hasOne('App\Models\Chat','id','chat_id');
    }
}
<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class Chat extends Model
{
    protected $fillable = ['name','id'];

    public function last_message()
    {
        return $this->hasOne('App\Models\ChatMessage')->orderBy('created_at', 'desc');
    }

    public function unread_messages_count()
    {
        return $this->hasMany('App\Models\ChatMessage')->where('read',0)->count();
    }
}

Связь со мной:
Скайп(с аватаркой) - shyraks
Телеграм - @Mramoris или +7 999 260 13 20

Не в сети

#2 24.05.2019 20:32:27

Re: Как получить количество сообщений из другой таблицы в orm запросе?

Варинаты которые я не знаю как приурочить

->with(['unread_messages_count' => function($query)
            {
                $query->orderBy('created_at', 'desc');
                MessageChat::where('active', 1)->where('read',0)->count();
            }])
             //->select(DB::raw('count(*) as chat_messages'))
           ->join('chat_messages', 'chat_messages.chat_id', '=', 'orders.user_id')
            ->select('users.id', 'contacts.phone', 'orders.price');

Связь со мной:
Скайп(с аватаркой) - shyraks
Телеграм - @Mramoris или +7 999 260 13 20

Не в сети

Подвал раздела