【问题标题】:Laravel - Eager loaded model functionLaravel - 渴望加载的模型功能
【发布时间】:2021-09-08 17:59:46
【问题描述】:

我正在尝试使用 Laravel 构建一些聊天系统,我有这两种模型:用户和线程

User 模型具有 Messagable Trait,您可以在其中获取所有线程

$user->threads();

我正在尝试使用以下方法将额外的数据加载到线程数组中:

$threads = Auth::user()->threads()->with(['participants.user'])->get();

我正在努力的是线程模型具有从中获取最新消息的功能:

$thread->getLatestMessage();

我的问题是如何将这条最新消息附加到我正在执行的上层查询中。我正在尝试这样的事情,但它不行......我想我在这里做了一些愚蠢的事情......

$threads = Auth::user()->threads()->with([
        'participants.user',
        'latestMessage' => function ($query) {
            return $query->getLatestMessageAttribute();
        }])->get();

$threads = Auth::user()->threads()->with(['participants.user','getLatestMessageAttribute'])->get();

我希望我能澄清这一点,因为我正在为这个系统使用第 3 方包,它具有我正在使用的这些 Traits 和 Thread 类。

解决方案

看起来我在获取集合时必须在末尾添加 append('accessor_name')。

$collection = Auth::user()->relationship()->get()->append('accessor_name');

【问题讨论】:

  • 尝试添加受保护的 $appends=['latest_message'];在线程模型中
  • 我也在考虑这个问题......但问题是线程模型来自包供应商。我怎样才能修改它或用我自己的覆盖 Thread 模型
  • 能否提一下包链接

标签: php laravel api relationship eager


【解决方案1】:

您可以覆盖类。创建新模型并扩展包模型

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;


class Thread extends \Lexx\ChatMessenger\Models\Thread
{
    use HasFactory;

    protected $appends=['latest_message'];
    

}

发布配置:

php artisan vendor:publish --provider="Lexx\ChatMessenger\ChatMessengerServiceProvider" --tag="config"

config/chatmessenger.php

'thread_model' => \App\Models\Thread::class,

更新 如果有人仍然没有得到属性数据,那么不要忘记清除缓存

php artisan cache:clear

php artisan optimize

php artisan config:clear

php artisan clear

【讨论】:

  • 我这样做了,现在当我尝试执行以下操作时... latest_message 不在对象 Auth::user()->threads()->with(['participants.user' ])->get();
  • 它可能不在对象中,但尝试访问该对象。同时尝试 public function getLatestMessageAttribute() { return $this->messages()->latest()->first(); } 这个方法在新模型中
  • @NenadKaevik.如果你使用 laravel 8 然后更新 'user_model' => App\Models\User::class,
  • 最后一个选项我可以创建新方法 public function latestMessage() { return $this->messages()->latest()->first(); } 和访问像 $thread->latestMessage();
  • 虽然这很奇怪......它应该像你上面提到的那样工作......我不知道tbh......无论如何人......感谢你的帮助:D终于弄清楚了... 万分感谢! ??
猜你喜欢
  • 1970-01-01
  • 2012-06-16
  • 2013-05-06
  • 1970-01-01
  • 1970-01-01
  • 2014-12-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多