Сортировать результаты в Laravel по таблице из отношений - PullRequest
0 голосов
/ 20 октября 2019

Я новичок в Laravel. Я использую в своем проекте Laravel 5.8.

У меня есть пользователь:

Schema::create('users', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->char('enable', 1)->default(0);
            $table->string('name', 120)->nullable();
            $table->string('surname', 120)->nullable();
            $table->string('email', 120)->unique();
            $table->timestamp('email_verified_at')->nullable();
            $table->string('password');
            $table->dateTime('last_activity')->nullable();
            $table->rememberToken();
            $table->timestamps();
            $table->engine = "InnoDB";
            $table->charset = 'utf8mb4';
            $table->collation = 'utf8mb4_unicode_ci';
        });


class User extends Authenticatable implements MustVerifyEmail
{
    use Notifiable;
    use psCMS\Presenters\UserPresenter;
    use scopeActiveTrait;

    public static $roles = [];
    public $dates = ['last_activity'];

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */

    protected $fillable = ['enable', 'name', 'surname', 'email', 'email_verified_at', 'password' 'remember_token', 'created_at', 'updated_at', 'last_login_at', 'last_login_ip'];


    /**
     * The attributes that should be hidden for arrays.
     *
     * @var array
     */

    protected $hidden = [
        'password', 'remember_token',
    ];

    public function comments()
    {
        return $this->hasMany('App\Comment');
    }

    public function userCommentsCount()
    {
        return $this->hasMany('App\Comment', 'commentable_id', 'id')->where('enable', '=', '1')->where('to_stats', '=', '0');
    }

public function scopeUserAvailable($query)
    {
        return $query->active()
            ->where('email_verified_at', '<>', null);
    }


}

и комментарии:

Schema::create('comments', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->bigInteger('user_id')->unsigned();
            $table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
            $table->string('commentable_type');
            $table->bigInteger('commentable_id');
            $table->char('enable', 1)->default(0);
            $table->char('to_stats', 1)->default(0);
            $table->tinyInteger('rating')->default(0);
            $table->text('content');
            $table->dateTime('date_time');
            $table->ipAddress('ip');
            $table->engine = "InnoDB";
            $table->charset = 'utf8mb4';
            $table->collation = 'utf8mb4_unicode_ci';

        });

class Comment extends Model
{

    use scopeActiveTrait;

    protected $quarded = ['id'];
    protected $fillable = ['content', 'enable', 'rating', 'user_id', 'commentable_type', 'commentable_id', 'date_time', 'ip'];
    public $timestamps = false;

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

    public function user()
    {
        return $this->belongsTo('App\User');
    }
}

В таблице комментариев у меня есть "rating" (значения)от 1 до 5).

У меня есть список пользователей:

$role = [];
        if ($userType == 1) {
            $role = ['UserNormal'];
        } elseif ($userType == 2) {
            $role = ['UserPremium'];
        }

        return User::ofRoleType($role)
            ->where(function ($q) use ($query, $sortColumn, $sortMethod) {
                $q->userAvailable()
                    ->orderBy($sortColumn, $sortMethod);
            })->orderBy('id', 'ASC)->paginate(15);

Как можно отсортировать по: a) количеству комментариев на пользователя (у пользователя много комментариев) b)размер голосов, поданных в рейтинге (у каждого пользователя много комментариев и много разных голосов)

??

Как мне это сделать?

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...