dongzi0850 2016-05-16 15:39
浏览 95
已采纳

Laravel Query Builder结果对象抛出“试图获取非对象属性”异常

This is one of those headscratchers where the error message is directly contradicted by the evidence on hand. I have the following method in a Laravel model called Family, which has an id field:

public function getFamilyName()
{
    $search_id = ( empty( $this->primary_id ) ) ? $this->id : $this->primary_id;
    $names = DB::select( 
        'SELECT GROUP_CONCAT(`last_name` ORDER BY `last_name` SEPARATOR \'/\' ) `name_list` 
        FROM (SELECT `last_name` 
              FROM `children`  
              WHERE `primary_id` IS NULL  
              AND `family_id`=?  
              UNION  
              SELECT `last_name`  
              FROM `parents`  
              WHERE `primary_id` IS NULL  
              AND `family_id`=?) `last_names`', 
        array($search_id, $search_id) );
    $nameList = $names[0]->name_list;
    return ($nameList=="") ? 'Unnamed': $nameList;
}   

This code has worked fine until earlier today, but is now throwing a Trying to get property of non-object exception at
$nameList = $names[0]->name_list.

I hadn't touched the method, so I'm at a loss as to what's gone wrong. I've done some quick and dirty investigation via thrown Exceptions using print_r, and determined the following:

  • For the family I'm working with, print_r($names) resolves to
    Array ( [0] => stdClass Object ( [name_list] => Esper-Smith/Smith ) )
  • print_r($names[0]) resolves to
    stdClass Object ( [name_list] => Esper-Smith/Smith )
  • print_r($names[0]->name_list) resolves to 'Esper-Smith/Smith'
  • print_r(is_object($names[0])) returns 1

So why am I getting an Exception that $names[0] is a non-object? Why is an Exception being thrown for an expression that can successfully be resolved by a print_r() call? I don't like it when my code starts getting cute...

  • 写回答

1条回答 默认 最新

  • du7133 2016-05-16 16:22
    关注

    As DB::Select wraps around PDO and makes use of the fetchMode property to choose between object or array, you need to ensure that your fetchMode is properly set before executing your queries.

    The Laravel Connection implements method setFetchMode which sets the default connection mode. This change will persist for all the remainder of the script execution so if you change it somewhere you need to remember to change it back to how the rest of your code expects it to be.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 程序不包含适用于入口点的静态Main方法
  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记