У меня есть эта модель, использующая laravel 5.8: Модель
Мне нужно получить все Relatorios
от одного User
.Я уже установил отношения с моделями следующим образом:
Клиент
public function relatorios(){
return $this->hasMany('App\models\Relatorio');
}
Пользователь:
public function cliente()
{
return $this->belongsTo('App\models\Cliente');
}
public function grupos(){
return $this->belongsToMany("App\models\Grupo", "acessos");
}
Grupo
public function color()
{
return $this->belongsTo('App\models\Color');
}
public function usuarios(){
return $this->belongsToMany('App\User', 'acessos');
}
public function relatorios(){
return $this->hasMany('App\models\Relatorio');
}
Relatorio
public function cliente()
{
return $this->belongsTo('App\models\Cliente');
}
public function grupo()
{
return $this->belongsTo('App\models\Grupo');
}
Мне нужно перечислить все Relatorios
по Group
из одного User
и фильтр по Cliente
.Пока я могу сделать это следующим образом:
$id = auth()->user()->id;
$obj = User::with('grupos.relatorios.cliente')->get()->find($id);
мой результат:
{
"id": 2,
"name": "renan",
"email": "renan.daher@dstec.com.br",
"email_verified_at": null,
"cliente_id": 2,
"created_at": "2019-09-18 18:08:45",
"updated_at": "2019-09-18 18:08:45",
"grupos": [
{
"id": 2,
"descricao": "Tribut\u00e1rio",
"color_id": 1,
"created_at": "2019-09-13 18:14:58",
"updated_at": "2019-09-13 18:14:58",
"pivot": {
"user_id": 2,
"grupo_id": 2
},
"relatorios": [
{
"id": 1,
"descricao": "Relat\u00f3rio de CDA",
"link": "www.google.com.br",
"cliente_id": 1,
"grupo_id": 2,
"created_at": "2019-09-16 15:23:45",
"updated_at": "2019-09-16 15:23:45",
"cliente": {
"id": 1,
"descricao": "PMNI",
"created_at": null,
"updated_at": null
}
},
Однако, как я могу фильтровать User-> client_id
с Report-> client_id
?
Изменить Mathieu Ferre изменения:
Спасибо за помощь, я сделал что-то вроде того, что вы написали:
$grupos = Grupo::whereHas('relatorios', function($query){
$id = auth()->user()->id;
$query->whereHas('cliente', function($query) use ($id){
$query->where('user_id', $id);
});
})->with('relatorios.cliente')->get();
return $grupos->toJson();
И у меня этоошибка:
SQLSTATE[42S22]: Column not found: 1054 Unknown column 'user_id' in 'where clause' (SQL: select * from `grupos` where exists (select * from `relatorios` where `grupos`.`id` = `relatorios`.`grupo_id` and exists (select * from `clientes` where `relatorios`.`cliente_id` = `clientes`.`id` and `user_id` = 1)))