【发布时间】:2019-09-19 13:35:44
【问题描述】:
我有这个使用 laravel 5.8 的模型: Model
我需要从一个User 中获取所有Relatorios。
我已经通过这种方式与模型建立了关系:
客户
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");
}
集团
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');
}
我需要从一个User 中按Group 列出所有Relatorios,并按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
}
},
但是,如何使用Report-> client_id 过滤User-> 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)))
【问题讨论】:
-
嗨 XLannes,欢迎来到 SO。我认为 Has one through 和 Has many through 是您正在寻找的,如果我理解了您的问题