[英]Call to undefined method with Eloquent in Laravel5.1
我正在使用Laravel 5.1並遇到錯誤
調用未定義的方法Illuminate \\ Database \\ Eloquent \\ Collection :: votes()
在存儲數據時。
商業模式
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class Business extends Model
{
public function votes()
{
return $this->hasMany('App\Models\Vote');
}
}
然后將表單POST請求發送到
$business = Business::where('business_area', $request->input('business_area'))->get();
$vote = $business->votes()->create($request->all());
return response()->json($vote, 201);
由於某種原因,它找不到表決方法。 我被卡住了。
確保已加載模型。
前
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Post extends Model
{
/**
* Get the comments for the blog post.
*/
public function comments()
{
return $this->hasMany('App\Comment');
}
}
記住,Eloquent會自動在
Comment
模型上確定正確的外鍵列。 按照慣例,Eloquent將采用擁有模型的“ snake case”名稱,並在其后綴_id
。 因此,對於此示例,Eloquent將假定Comment model
上的外鍵是post_id
。
您可以對單個模型實例而不對集合進行投票。 因此,先在$ business上進行foreach操作,然后再對單個實例進行投票。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.