【问题标题】:How to Implement or where in Laravel Eloquent with post method array data?如何使用 post 方法数组数据在 Laravel Eloquent 中实现或在哪里实现?
【发布时间】:2020-07-21 19:37:35
【问题描述】:

我想在 Laravel Controller 中实现 Eloquent Search,这是 mysql 中的示例查询

  SELECT * FROM trx_order_ecommerce WHERE city LIKE '%Depok%' OR city LIKE '%Bogor%'

我使用 POST 方法来检索城市数据,

array:3 [▼
  0 => "Depok"
  1 => "Bogor"
  2=> ,....
]

这是我的控制器中的代码

$data = DataOrderEcommerce::orderBy('created_at','desc');
    if(isset($request->city_name))
            {
                $dat = $request->city_name;
                for ($i=0; $i < count($dat) ; $i++) { 
                    if($i=0){
                        $data->Where('city', 'like', '%'.$dat[$i]. '%' );
                    }
                    elseif($i>0){
                        $data->OrWhere('city', 'like', '%'.$dat[$i]. '%' );
                    }
                    else{
    
                    }
                }
               $data->get()
            }

但我没有得到任何数据,..

【问题讨论】:

  • 你在某处-&gt;get()你的数据吗?
  • 是的,.. 但我仍然没有得到数据
  • 您可以改用-&gt;toSql() 并查看查询,在phpMyAdmin 等中运行它并确保您得到结果/查询正常
  • @MuamarHumadi 你为什么使用LIKE %?您在数据库中的城市名称与请求中发送的城市名称不同吗?

标签: mysql laravel eloquent


【解决方案1】:

试试这样:

$query = DataOrderEcommerce::query();
if($request->has('city_name'))
{
$query->whereIn('city', $request->city_name);
}
$query->orderBy('created_at','desc')->get();

【讨论】:

【解决方案2】:

试试这个方法:

$data = DataOrderEcommerce::orderByDesc('created_at')
    ->when($request->has('city_name'), function($q) use ($request)
        {
            foreach($request->city_name as $key => $city) {
                if ($key == 0) {
                    $q->where('city', 'like', '%'.$city. '%' );
                } else {
                    $q->orWhere('city', 'like', '%'.$city. '%' );
                }
            }
        })->get();

【讨论】:

    猜你喜欢
    • 2019-11-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-06-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多