2016-06-29 24 views
0

的關係考慮一個模型僱員和模型項目Laravel /流明 - 限定與參數

僱員表有一個屬性類型可以分配下列值「1」, 「2」, 「3」 等

項目的hasMany僱員

public function programmers() { 
    return $this->hasMany('App\Employee') 
     ->where('type', '1'); 
} // hasMany programmers 

public function testers() { 
    return $this->hasMany('App\Employee') 
     ->where('type', '2'); 
} // hasMany testers 

public function managers() { 
    return $this->hasMany('App\Employee') 
     ->where('type', '3'); 
} // hasMany managers 

相反,這些關係的,我想只有一個:

public function employees($type_id) { 
    return $this->hasMany('App\Employee') 
     ->where('type', $type_id); 
} // hasMany employees 

它的工作是這樣的:

$app->get('/employee', function() { 
    $project = App\Employee::find(1); 
    return $project->employees("1"); 
}); 

不過,我收到以下異常:

ErrorException in Response.php line 402: 
Object of class Illuminate\Database\Eloquent\Relations\HasMany could not be converted to string 

回答

1

查看錯誤消息的內容:

ErrorException在Response.php線402: 對象類照亮\數據庫\鋒\關係\的hasMany不能轉換爲字符串

的錯誤發生在Response類中。這個錯誤是來了的原因是因爲你在你的路由定義返回關係而非響應

$app->get('/employee', function() { 
    $project = App\Employee::find(1); 
    return $project->employees("1"); 
}); 

一個關係對象不能轉換爲字符串,所以Response類不知道該怎麼辦。

如果您想檢查瀏覽器中關係查詢的結果,則需要返回valid response

試着改變你的路線是這樣的:你的查詢JSON的

$app->get('/employee', function() { 
    $project = App\Employee::find(1); 
    return response()->json($project->employees("1")->get()); 
}); 

這將輸出結果。還請注意使用get()。這確保關係查詢實際執行。

+0

謝謝,也爲廣泛的解釋 –