【问题标题】:Laravel multiple search in related tablesLaravel 在相关表中多次搜索
【发布时间】:2017-06-03 21:50:22
【问题描述】:

我有两张与城镇相关的表格。 (城镇属于城市,城市有很多城镇)

城镇表: id, name, city_id

城市表: 身份证、姓名

对于自动完成的 ajax 查询,我可以像这样通过 sql 查询得到结果。

Select t.id AS townid, t.name AS townname, c.name AS cityname FROM towns t 
left join cities c ON t.city_id=c.id
where t.name like '%ana%' OR c.name like '%ana%';

所以我得到了我想要的结果。但是在laravel中我无法做到这一点。 我可以搜索城镇但不搜索城市名称。

    $towns = App\Town::with('city')->where('name', 'like', '%ana%')->get();

【问题讨论】:

    标签: mysql laravel eloquent left-join


    【解决方案1】:

    试试下面的代码

    $towns= DB::table('towns')
         ->join('cities', 'cities.id', '=', 'towns.city_id')
         ->select('towns.id as townid', 'towns.name as towname', 'cities.name as cityname')
         ->where('towname', 'like', '%ana%')
         ->orWhere('cityname', 'like', '%ana%') 
         ->get();
    

    【讨论】:

      【解决方案2】:

      Laravel Elequent with() 不会加入,所以你无法在城镇中搜索。

      要进行与 abouse 相同的查询,您必须使用正确的 laravel 连接。

      比如:

      $towns = App\Town::leftJoin('cities', 'towns.city_id', '=', 'cities.id')
      ->where('towns.name', 'like', '%ana%')->orWhere('cities.name', 'like', '%ana%')->get();
      

      但在这个例子中,请检查选择了什么。您还可以指定要选择的字段 (select('towns.id', 'towns.name', ...))。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2021-02-27
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-02-07
        • 2023-03-18
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多