2016-11-03 41 views
1

我已經定義了以下關係到我的車型& B:關係表中Laravel不承認5

A型

namespace App; 

use Illuminate\Database\Eloquent\Model; 

class A extends Model { 

protected $table = 'list'; 

public function b(){ 

    return $this->hasMany('App\B', 'id', 'id'); 

    } 
} 

B型

namespace App; 

use Illuminate\Database\Eloquent\Model; 

class B extends Model 
{ 

protected $table = 'project'; 

public function a(){ 

    return $this->belongsTo('App\A', 'id', 'id'); 

} 

}

我想從基於從模型A.但是選擇模型B中的總和,它返回一個錯誤未定義的屬性:照亮\數據庫\雄辯\收藏:: $ B

控制器

public function index() 
{ 
    $all = A::all()->count(); 
    $large = A::where('class', 'L')->count(); 
    $medium = A::where('class', 'M')->count(); 

    $lg = A::where('class','L')->get(); 
    $amount = $lg->b->sum('value'); 

    return view('srl')->with('large', $large) 
         ->with('medium',$medium) 
         ->with('all',$all) 
         ->with('amount',$amount); 
} 

的問題是在這條線$amount = $lg->b->sum('value');。由於某種原因,這種關係似乎不起作用。任何建議,將不勝感激。

回答

0

您試圖在集合上獲得關係,該關係存在於該集合中的對象(記錄)上。您需要遍歷$lg結果,併爲每個結果獲取其值b

事情是這樣的:

$lg = A::where('class','L')->get(); 
$amount = 0; 
foreach($lg as $item) 
{ 
    $amount += $item->b->value; 
} 
0

感謝@詹姆斯......我不得不雙環得到它的工作。我不知道爲什麼我必須循環兩次。