【问题标题】:where query from table with column foreign keywhere 从具有列外键的表中查询
【发布时间】:2017-05-15 13:29:34
【问题描述】:

我有表列表和城市,列表有一个城市的关系。 有两个输入,第一个输入是查看列表名称,第二个输入是查看城市名称。 Listings 表有列名和city_id。 Cities 表具有列 ID 和名称。

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

当前查询如下所示

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

这给出了未知的错误列

SQLSTATE[42S22]: 找不到列: 1054 'where 子句'中的未知列'%city input%' (SQL: select count(*) as aggregate from listings where name LIKE %listing input% and %city input% LIKE(选择 * whereities.name 为空))

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

【问题讨论】:

    标签: mysql laravel laravel-5 laravel-5.3


    【解决方案1】:

    我认为whereHas 是您所需要的。

    假设你的关系被称为“城市”:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-01-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-01-22
      • 1970-01-01
      • 2020-11-15
      相关资源
      最近更新 更多