我有一个游戏模型,与位置模型有关系。
我想在游戏名称字段以及游戏位置名称字段中进行搜索。并且游戏的开始时间必须大于今天的日期。
$games = Game::with('user', 'location')
->when($this->searchterm !== '', fn(Builder $query)
=> $query->where('name', 'like', '%'. $this->searchterm .'%')->orWhere('location.name', 'like', '%'. $this->searchterm .'%')
)
->orderBy('start_time', 'ASC')
->whereDate('end_time', '>', Carbon::now())
->paginate(100);
这行不通。它抛出以下错误:
未找到列:1054“where 子句”中的未知列“location.name”
如何解决这个问题?
当 Eloquent 加载关系时(在您的情况下,通过
Game
加载 user
的 location
和 with('user', 'location')
关系),它不会在主查询上使用连接,这意味着您不能简单地使用 where
/orWhere
就像您尝试过的那样。
相反,你需要专门使用 Eloquent 方法来查询关系是否存在
$games = Game::query()
->with('user', 'location')
->when(
$this->searchterm !== '',
fn (Builder $query) => $query
->where('name', 'like', "%{$this->searchterm}%")
->orWhereRelation('location', 'name', 'like', "%{$this->searchterm}%")
)
->orderBy('start_time', 'ASC')
->whereDate('end_time', '>', Carbon::now())
->paginate(100);
whereHas
/orWhereHas
)whereRelation
/orWhereRelation
)