Отсортировать в ларавел чеерез промежуточную таблицу много ко многим
Помогите сделать сортировку. Есть таблицы
create table devices
(
id bigint unsigned auto_increment
primary key,
number varchar(64) null,
code int unsigned null,
counter varchar(255) default '' not null,
date_check datetime null,
last_answer datetime null,
device_type_id bigint unsigned not null,
status tinyint not null,
device_place_id bigint unsigned not null,
location_id bigint unsigned not null,
created_at timestamp null,
updated_at timestamp null,
raw_data text not null,
personal_number varchar(255) default '' not null)
create table parameters
(
id bigint unsigned auto_increment
primary key,
name varchar(255) default '' not null,
device_type_id int not null,
title varchar(255) default '' not null
)
create table device_parameter
(
device_id bigint unsigned not null,
parameter_id bigint unsigned not null,
value float null,
date datetime null,
id bigint unsigned auto_increment
primary key,
created_at timestamp null,
updated_at timestamp null,
constraint device_parameter_device_id_foreign
foreign key (device_id) references devices (id),
constraint device_parameter_parameter_id_foreign
foreign key (parameter_id) references parameters (id)
)
И модели В Device.php
public function parameters() {
/***
* device(id) -> device_data(device_id)
*/
return $this->belongsToMany(Parameter::class)->withPivot('value', 'date')->orderBy('date', 'desc');
}
public function value() {
return $this->belongsToMany(DeviceParameter::class,'device_parameter');
}
В parameter.php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Parameter extends Model
{
use HasFactory;
}
В таблицу device_parameters заносяться показания приборов по датам и код параметра. Мне нужно отсортировать таблицу devices по последним значениям из столбца device_parameter.value от большего к меньшему и наоборот. Так же возможна фильтрация по дате показаний. Использую
$this->query->join('device_parameter', 'devices.id', '=', 'device_parameter.device_id')
->where('device_parameter.parameter_id',1)
->orderBy('device_parameter.value','ASC');
Но получаю дублирующие записи. Как сделать правильно ?
Источник: Stack Overflow на русском