2016-06-23 35 views
1

你們能告訴我我的代碼有什麼問題嗎? 這裏的代碼L5 - 錯誤:試圖獲取非對象的屬性(奇怪的情況)

$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的線,因爲試圖獲得非對象的屬性。然而,下面是我打印$ 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-> ID

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; 
} 

對此代碼感到沮喪,任何幫助表示讚賞。

+0

您能否發佈確切的錯誤信息?在調用' - > get()'方法時,你可能會得到'non object'錯誤信息? – codedge

+0

哎呀,看起來像是出了點問題。 1/1 HomeController.php中的ErrorException異常第154行:試圖獲取非對象的屬性 –

+0

請編輯您的原始文章並在其中輸入錯誤消息。還要添加你的HomeComtroller.php,這樣我們就可以看到發生了什麼。 – codedge

回答

0

我發現了我找到的最奇怪的解決方案。

如上所述,問題是爲什麼$ datax-> id不能使用但打印?

這裏是解決方案:你可以使用它作爲$datax['id']$datax->id

有人可以解釋這到底是怎麼工作的?

對不起我的英語,我希望這會對你有所幫助,你也可以幫我回答我最後一個問題。

0

那麼,訪問數據如$datax['id']你通常會做$datax數組。 訪問數據如使用$datax->id如果$datax對象

您的\App\AccountsScoreHistory模型有望延伸Illuminate\Database\Eloquent\Model使用$model->property訪問模型屬性。

相關問題