来自 table 的带有列外键的查询

where query from table with column foreign key

我有table个房源和城市,房源有一个城市的关系。 有 2 个输入,第一个输入是查看列表名称,第二个输入是查看城市名称。 列表 table 具有列名称和 city_id。 城市 table 有列 ID 和名称。

目标是在城市输入中查找列表。

当前查询看起来像这样

$listings = Listing::where('name', 'LIKE', '%'. $request->search. '%')->where('%'. $request->location. '%', 'LIKE', function($query){
            $query->where(DB::raw('cities.name'));
        })->paginate(10);

这给出了未知的错误列

SQLSTATE[42S22]: Column not found: 1054 Unknown column '%city input%' in 'where clause' (SQL: select count(*) as aggregate from listings where name LIKE %listing input% and %city input% LIKE (select * where cities.name is null))

有什么办法解决这个问题吗?

我认为whereHas是你需要的。

假设你们的关系叫做"city":

$listings = Listing::where('name', 'LIKE', '%' . $request->search . '%')
    ->whereHas('city', function($query) use($request) {
        $query->where('name', 'LIKE', '%' . $request->location . '%');
    })
    ->paginate(10);