mysql - 渴望加载: How to get a few photos from table with polymorph relationship

标签 mysql laravel-5 eloquent

我不会获取带有头像和 4 张照片的用户列表,如屏幕截图所示:enter image description here

用户模型:

   public function avatar()
   {
      return $this->morphOne(Photo::class, 'photoable')
        ->where('photoable_type', 'user');
   }

   public function photos()
   {
     return $this->morphMany(Photo::class, 'photoable')
        ->where('photoable_type', 'photo');
   }

   public function scopeLastPhotos($query)
   {
      return $query->with(['photos' => function ($query) {

         $query->take(4)->get();

      }]);
   }

照片模型:

   public function photoable()
   {
      return $this->morphTo();
   }

我尝试过:

$users = User::with('avatar')->lastPhotos()->get();

但结果只有头像和空照片集:

enter image description here

所有照片都存在于表格中。

最佳答案

我用 mysql 函数“group_concat”解决了这个问题:

public function scopeLastPhotos($query)
{
   return $query->join('photos', 'photos.photoable_id', 'users.id')
        ->selectRaw('users.*, group_concat(photos.hash) as hashes')
        ->where('photos.photoable_type', 'photo')
        ->groupBy('photos.photoable_id');
}

但是“group_concat”没有“限制”https://bugs.mysql.com/bug.php?id=30098 .

对于我的任务,我使用了这个决定:

@foreach(explode(',', $user->hashes) as $hash)

    {{ $hash }}

    @break($loop->iteration == 4)

@endforeach

但也许有人知道更优雅的解决方案?

关于mysql - 渴望加载: How to get a few photos from table with polymorph relationship,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44678528/

相关文章:

php/mysql - 从一个表中选择 id 除了在另一个表中的 id

php - Eloquent BelongsToMany 关系搜索为空

php - 从相关模型 laravel 获取 id

php - Laravel Eloquent Query 根据设定的条件查询多条记录

php - Laravel 中 undefined variable : task (View: C:\Users\13\Desktop\TDT\resources\views\files\form.blade.php)

php - 如何创建用户事件日志?

PHP 打印使用 While 循环和数组返回的所有值

laravel - 困惑 - AppServiceProvider.php 与 app.php

php - Laravel 5 图片上传不正确的数据库路径

php - Laravel 5.4 - 根据用户请求订购数据