L5 - 错误:试图获取非对象的属性(奇怪的情况)

时间:2016-06-23 09:30:50

标签: php laravel object laravel-5 eloquent

你们能告诉我我的代码有什么问题吗? 这是代码

$datax = \App\AccountsScore::where('account_id', $account_id)
    ->where('score_id', $score->id)
    ->first();

$datav = \App\AccountsScoreHistory::where(
    'account_score_id', $datax->id
)->get();
由于试图获取非对象的属性,我在$ datav&line的行上出错了。但是,下面是我打印$ datax或$ datax-> id。

的结果

$ DATAX

App\AccountsScore Object (
[connection:protected] => riskserver
[table:protected] => accounts_score
[primaryKey:protected] => id
[keyType:protected] => int
[perPage:protected] => 15
[incrementing] => 1
[timestamps] => 1
[attributes:protected] => Array (
    [id] => 24467
    [account_id] => 114
    [score_id] => 14
    [value] => 8 )
[original:protected] => Array (
    [id] => 24467
    [account_id] => 114
    [score_id] => 14
    [value] => 8 )
[relations:protected] => Array ( )
[hidden:protected] => Array ( )
[visible:protected] => Array ( )
[appends:protected] => Array ( )
[fillable:protected] => Array ( )
[guarded:protected] => Array (
    [0] => * )
[dates:protected] => Array ( )
[dateFormat:protected] =>
[casts:protected] => Array ( )
[touches:protected] => Array ( )
[observables:protected] => Array ( )
[with:protected] => Array ( )
[morphClass:protected] =>
[exists] => 1
[wasRecentlyCreated] =>
) 

$ datax->编号

24467

这里是错误消息

Whoops, looks like something went wrong. 
1/1 ErrorException in HomeController.php line 154: Trying to get property of non-object

这是我的HomeController.php(第145 - 166行)

function getTotalScore($name='', $account_id)
{
    if(strlen($name) > 0)
    {
        $score = Score::where('name', $name)->first();
        if(!$score) return 0 ;

        $score_id = $score->id;
        $datax = \App\AccountsScore::where('account_id', $account_id)->where('score_id', $score->id)->first();
        /* line 154 */ $datav = \App\AccountsScoreHistory::whereRaw('account_score_id = '.$datax->id)->get();
        $countdatas = count($datav);
        if($countdatas == null){
            $countdatas = 0;
        }
        return $countdatas;
    }
    else{
        $data = AccountsScore::select(DB::raw('ifnull(sum(value),0) AS total'))->where('account_id', $account_id)->first();
        return $data->total;
    }
    return 0;
}

对这段代码感到沮丧,任何帮助都表示赞赏。

2 个答案:

答案 0 :(得分:0)

我找到了我发现的最奇怪的解决方案。

如上所述,问题是为什么$ datax-> id不能被使用但是打印?

以下是解决方案:您可以将其用作space而不是$datax['id']

有人可以解释这是如何起作用的吗?

抱歉我的英语,我希望这对你有帮助,你也可以帮我回答我的最后一个问题。

答案 1 :(得分:0)

好吧,如果$datax['id']数组,那么访问$datax这样的数据就是正常的。 如果$datax->id对象,则访问$datax之类的数据。

您的\App\AccountsScoreHistory模型希望扩展Illuminate\Database\Eloquent\Model以使用$model->property访问模型属性。