gpt4 book ai didi

php - 当两个表具有相同的列名时,连接关系表后对模型进行排序

转载 作者:行者123 更新时间:2023-11-29 09:30:13 25 4
gpt4 key购买 nike

我正在 Laravel 上构建一个应用程序,其中有 ProjectLatestStatus 模型,我有一个表,其中包含分拣设施。所以我可以按名称、最新状态、最后更新时间等进行排序。所以这个架构是:

projects
id
name -> string
state -> string
region -> string
status -> enum ('saved', 'draft')
created_at -> timestamp
updated_at -> timestamp

project_latest_status
id
project_id -> integer // (project id foreign key)
status -> string // (current status of project)

我想通过加入 latest_status 表对项目进行排序,并根据项目的当前状态进行排序。为此我尝试了这样的事情:

Project::where('status', 'saved')
->when( $request->name , function( $q) use( $request ) {
$q->where('name', 'like', '%' . $request->name .'%');
})
->when($request->status, function ($q) use($request) {
$q->whereHas('latestStatus', function ($q) use($request){
$q->whereHas('status', function ($q) use($request) {
$q->whereIn('name', collect($request->status)->pluck('name') );
});
});
})
->when($request->sort_by_column, function ($q) use($request) {
$q->when($request->sort_by_column['column'] == 'name' || $request->sort_by_column['column'] == 'website', function ($q) use($request) {
$q->orderBy($request->sort_by_column['column'], $request->sort_by_column['order'] );
})
->when($request->sort_by_column['column'] == 'added_date' , function ($q) use ($request) {
$q->orderBy('created_at', $request->sort_by_column['order']);
})
->when($request->sort_by_column['column'] == 'status', function ($q) use ($request) {
$q->join('project_latest_status', 'projects.id', '=', 'project_latest_status.project_id')
->join('project_status', 'project_latest_status.status', '=', 'project_status.id')
->select('projects.*', 'project_status.name as status_name')
->orderBy('status_name', $request->sort_by_column['order']);
})
})->get();

一切正常,但一旦我单击状态排序,就会出现错误:

SQLSTATE[23000]: Integrity constraint violation: 1052 Column 'status' in where clause is ambiguous (SQL: select count(*) as aggregate from projects inner join project_latest_status on projects.id = project_latest_status.project_id inner join project_status on project_latest_status.status = project_status.id where status = saved and projects.deleted_at is null)"

帮我解决这个问题。谢谢

最佳答案

更改来源

where('status', 'saved')

where('projects.status', 'saved')

或者在任何地方将 status 与另一个连接表另一个相同的字段一起使用,因此您需要指定要按 status 过滤的表

关于php - 当两个表具有相同的列名时,连接关系表后对模型进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58889900/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com