Laravel Eloquent关联表OR条件查询报错,求解决方法
修复方案说明
报错原因是with('location')只是预加载关联模型数据,不会在主查询中关联location表,直接写location.name会导致数据库找不到该字段——因为主查询仅查询games表。以下是两种可行的修复方式:
方式一:使用whereHas筛选关联模型(推荐)
通过whereHas针对关联的Location模型添加查询条件,适合仅需筛选Game模型的场景:
use Illuminate\Database\Eloquent\Builder; use Carbon\Carbon; $games = Game::with('user', 'location') ->when($this->searchterm !== '', function (Builder $query) { $searchTerm = '%' . $this->searchterm . '%'; $query->where('name', 'like', $searchTerm) // 筛选关联的Location名称匹配的Game ->orWhereHas('location', function (Builder $subQuery) use ($searchTerm) { $subQuery->where('name', 'like', $searchTerm); }); }) ->orderBy('start_time', 'ASC') // 修正:原需求是start_time大于当前日期,替换原代码的end_time ->whereDate('start_time', '>', Carbon::now()) ->paginate(100);
方式二:使用join关联表查询
直接关联locations表(注意Laravel默认表名为复数,若自定义表名需对应修改),可以直接在where中引用关联表字段:
use Illuminate\Database\Eloquent\Builder; use Carbon\Carbon; $games = Game::with('user', 'location') // 关联locations表,需确保外键字段正确(此处假设Game的外键是location_id) ->join('locations', 'games.location_id', '=', 'locations.id') ->when($this->searchterm !== '', function (Builder $query) { $searchTerm = '%' . $this->searchterm . '%'; // 必须指定表前缀,避免字段名冲突 $query->where('games.name', 'like', $searchTerm) ->orWhere('locations.name', 'like', $searchTerm); }) ->orderBy('games.start_time', 'ASC') ->whereDate('games.start_time', '>', Carbon::now()) // 仅选择games表的字段,避免关联表字段覆盖或冲突 ->select('games.*') ->paginate(100);
额外注意
原代码中写的是whereDate('end_time', '>', Carbon::now()),但你的需求是Game的start_time需大于当前日期,所以需要修正为start_time。
内容的提问来源于stack exchange,提问作者J K
相关产品推荐
相关产品推荐

