【问题标题】:Difficult to get the element out of this array很难从这个数组中取出元素
【发布时间】:2019-02-26 09:23:04
【问题描述】:

在我的 Laravel 应用程序中,我尝试仅在一个元素内访问数组中的文本,但它给了我错误。

$account_id = DB::select('select id from chart_of_accounts where type =\'Expense\' LIMIT '.$request->account_id.',1;');
return $account_id[0];

错误信息:

The Response content must be a string or object implementing __toString(), "object" given.

如果我全部退回:

return $account_id;

输出:

[{"id":19}]

我不知道如何将这个数组转换为单个字符串?

【问题讨论】:

    标签: php arrays laravel


    【解决方案1】:

    laravel DB::select() 函数返回一个对象数组,如Laravel documentation 中所述:

    select 方法将始终返回array 的结果。数组中的每个结果都是一个 PHP StdClass 对象,允许您访问结果的值

    您需要访问对象的id 属性:

    $account_id = DB::select('select id from chart_of_accounts where type =\'Expense\' LIMIT '.$request->account_id.',1;');
    return $account_id[0]->id;
    

    【讨论】:

      【解决方案2】:

      最好用这种查询方式

      $account = DB::table('chart_of_accounts')
                      ->select('id')
                      ->where('id', $request->account_id)
                      ->where('type', 'Expense')
                      ->take(1)
                      ->first();
      
      return $account->id;
      

      但对于偏移:

      $account = DB::table('chart_of_accounts')
                      ->select('id')
                      ->where('type', 'Expense')
                      ->offset($request->account_id)
                      ->take(1)
                      ->first();
      
      return $account->id;
      

      【讨论】:

      • 有没有办法将 SQL 语法 Limit(1,2) 转换为查询生成器?
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-11-26
      • 2014-01-06
      • 2017-11-17
      • 1970-01-01
      • 1970-01-01
      • 2019-07-19
      • 1970-01-01
      相关资源
      最近更新 更多