【问题标题】:Retrieving data from database using multiple ids - Laravel使用多个 id 从数据库中检索数据 - Laravel
【发布时间】:2017-11-24 22:21:24
【问题描述】:

我的数据库中有具有唯一 ID 的客户列表。我正在尝试使用像这样的这些唯一 ID 来检索这些客户。

我想获取每个客户的姓名和电话,以便分别处理给他们的消息。但是根据我的查询,我只得到一个客户,而不是我的所有客户。

PS:当我返回 $explode 时,我能够得到我选择的所有 id。

  public function getCustomers(Request $request)
     {
        $ids = $request->ids; 

        $explode = explode(",",$ids);

        if(request()->ajax())
        {


        $clients = Client::whereHas('product', function($find_clients)use($explode)
            {
                 $find_clients->where('id',$explode);

            })->get(); 

           $get_customer_name = [];
           $get_customer_phone = [];

            foreach($clients as $key => $client)
            {
                $get_customer_name[] = $client->name;
                $get_customer_phone [] = $client->phone;

                return ['success' => $explode];                                
            }            
           }
}

短信查询

$query = "?key=$api_keyto=$implode(',',$$get_customer_phone)&msg=Dear ".$implode(',',$$get_customer_name)."Thank you";

【问题讨论】:

  • 您是针对客户表中的所有客户,还是针对特定产品的客户?
  • 唯一的客户端 ID 在哪里?看起来该查询正在尝试通过存在产品 ID 而非客户端 ID 的 product 关系来过滤客户端
  • @robbyrr 我的目标客户是拥有具有唯一 ID 的产品的客户。这些产品具有唯一的 ID,它们属于特定的客户。所以我正在寻找那些拥有这些唯一 ID 的客户(即拥有这些产品的客户
  • @lagbox 是的,产品具有这些唯一 ID。一些客户拥有这些产品,因此拥有这些产品。所以我试图根据产品的唯一 ID 找到这些客户。
  • 你有建立关系吗? Like product belongsTo..or 共享客户表和产品表/迁移

标签: php laravel


【解决方案1】:

要查找具有一组 id 的客户端,请尝试使用 whereIn 而不是 where。

像这样:

$find_clients->whereIn('id',$explode);

【讨论】:

    【解决方案2】:

    尝试使用 whereIn 而不是 where

    $find_clients->whereIn('id', $explode);
    

    【讨论】:

    • return ['success' => implode(',',$get_customer_name)]; 只返回一位客户的姓名,尽管我选择了很多 ID
    • 会不会是ajax请求不允许循环?
    • @XamarinDevil 因为您正在循环中进行返回
    • @lagbox,即使返回在循环之外,它也只返回一个名字
    • 试试 dd($explode) 和 dd($clients)
    猜你喜欢
    • 2013-05-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-01-02
    • 2021-09-24
    • 1970-01-01
    • 2012-12-26
    • 1970-01-01
    相关资源
    最近更新 更多