我如何hasMany关系,得到最后的5个用户,我尝试使用模型和巫婆hasMany的关系出现空。我已经做了很多测试,在每次查询中获得最后5个用户时,我总是遇到关系问题。
查询:
$minute = Minute_Report::Query()->whereBetween('minutos.fecha', [$from, $to])
->join('clients', 'minutos.cliente', '=', 'clients.id')
->join('users as asesor', 'minutos.psiquico', '=', 'asesor.id')
->select(
'minutos.id',
'clients.code',
'clients.id as client',
\DB::raw("CONCAT(clients.firstname_c,clients.lastname_c) As client_full_name"),
\DB::raw("CONCAT(asesor.first_name,asesor.last_name) As asesor_full_name"),
'minutos.date2 As fechas',
'minutos.minutos',
\DB::raw('(CASE
WHEN minutos.motive = "MINUTOS GRATIS" THEN "GRATIS"
ELSE "PAGO"
END) AS status_lable'),
'minutos.motive',
'minutos.time_a',
);
$data = $minute->get();结果:
[
asesor_full_name: "Lucero /Liliana Fuentes"
client: 2079
client_full_name: "NICOLE MSALLS OCACIO"
code: 2078
fechas: "2021-01-01 09:40:44"
id: 64208
minutos: 27
motive: "MINUTOS GRATIS"
status_lable: "GRATIS"
time_a: "40"
]成功:
[
asesor_full_name: "Lucero /Liliana Fuentes"
client: 2079
client_full_name: "NICOLE MSALLS OCACIO"
code: 2078
fechas: "2021-01-01 09:40:44"
id: 64208
minutos: 27
motive: "MINUTOS GRATIS"
status_lable: "GRATIS"
time_a: "40"
users[
1,
2,
3,
5
]
]发布于 2022-01-15 19:34:46
我不知道我做得对不对,但我会尽力帮忙的。
您在Minute_Report模型中定义了与用户模型的关系吗?什么是关系栏?应该就像
public function users()
{
return $this->hasMany(User::class, 'xxx');
}在你的Minute_Report模型上。'xxx‘指的是用户表上的关系列名。
然后,您应该在查询中添加“with(‘user’)”。就像这样:
$minute = Minute_Report::Query()->whereBetween('minutos.fecha', [$from, $to])
->join('clients', 'minutos.cliente', '=', 'clients.id')
->join('users as asesor', 'minutos.psiquico', '=', 'asesor.id')
->select(
'minutos.id',
'clients.code',
'clients.id as client',
\DB::raw("CONCAT(clients.firstname_c,clients.lastname_c) As client_full_name"),
\DB::raw("CONCAT(asesor.first_name,asesor.last_name) As asesor_full_name"),
'minutos.date2 As fechas',
'minutos.minutos',
\DB::raw('(CASE
WHEN minutos.motive = "MINUTOS GRATIS" THEN "GRATIS"
ELSE "PAGO"
END) AS status_lable'),
'minutos.motive',
'minutos.time_a',
)->with('users');
$data = $minute->get();https://stackoverflow.com/questions/70722943
复制相似问题