如何在一项请求中从父母那里获得5条儿童记录?

时间:2019-05-19 17:21:10

标签: eloquent laravel-5.7

//Request

     $messages = ChatMessage::where('user_id', Auth::id())
            ->orderBy('created_at', 'asc')
            ->select(['chat_id'])
            ->take(5)
            ->distinct()
            ->with('chat.last_messages')
            ->get();

$messages = ChatMessage::where('user_id', Auth::id())
    ->orderBy('created_at', 'asc')
    ->select(['chat_id'])
    ->take(5)
    ->distinct()
    //->with('chat.last_messages')
    ->with(['chat'=>function($query) {
        $query->with(['last_messages'=>function($query) {
            $query->limit(5);
        }]);
    }])
    ->get();

//Class Message

    <?php
    
    namespace App\Models;
    
    use Illuminate\Database\Eloquent\Model;
    
    class ChatMessage extends Model
    {
        protected $fillable = ['chat_id','user_id', 'text'];
    
        public function user()
        {
            return $this->hasOne('App\Model\UserFieldsValues','id','user_id')/*->take(5)*/->select(['id','value']);
        }
    
        public function chat()
        {
            return $this->hasOne('App\Models\Chat','id','chat_id');
        }
    }

//Class Chat

    <?php
    
    namespace App\Models;
    
    use Illuminate\Database\Eloquent\Model;
    
    class Chat extends Model
    {
        protected $fillable = ['name','id'];
    
        public function last_messages()
        {
            return $this->hasMany('App\Models\ChatMessage')->orderBy('created_at', 'asc')->limit(5);
        }
    
        public function unread_messages()
        {
            return $this->hasMany('App\Models\ChatMessage')->orderBy('created_at', 'asc')->where('read',0)->take(5);
        }
    }


///

如何在一个请求中从父母那里获得5条子记录?

目前,从数据库中获取的所有聊天消息均为5条,而不是每条消息的5条。

令人沮丧的文本向下验证消息站点 ................................................... ................................................... //////////////

1 个答案:

答案 0 :(得分:0)

Laravel中没有对此的本地支持。

我为此创建了一个包:https://github.com/staudenmeir/eloquent-eager-limit

在父模型和相关模型中都使用fflush()特性。

HasEagerLimit

然后,您可以将class Chat extends Model { use \Staudenmeir\EloquentEagerLimit\HasEagerLimit; } class ChatMessage extends Model { use \Staudenmeir\EloquentEagerLimit\HasEagerLimit; } / ->limit(5)应用于您的关系。