Laravel 5.1 - 关系方法必须返回一个类型的对象
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/31967154/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Laravel 5.1 - Relationship method must return an object of type
提问by Sam
My application takes payment from users but sub accounts must not be allowed to see the payment screen.
我的应用程序从用户那里接受付款,但不允许子帐户看到付款屏幕。
I have a Route::group
which checks if the user is allowed to pay through Middleware. The handle
function look like this
我有一个Route::group
检查是否允许用户通过中间件付款。该handle
功能这个样子的
if(!\Auth::user()->isTeacher)
{
\Auth::logout();
return redirect('/login')->withErrors([$error = 'Sorry there was a problem. Please notify your School']);
}
return $next($request);
and the isTeacher()
function
和isTeacher()
功能
if($this->school_id) {
$teachers = $this->school->find($this->id)->teachers;
$isTeacher = false;
foreach ($teachers as $teacher) {
if ($teacher->id == \Auth::user()->id) {$teacher = true;}
}
return $isTeacher;
}
}
Finally the School relationship looks like the following
最后,学校关系如下所示
return $this->hasOne('App\School', 'id', 'school_id');
The error I keep receiving is
我不断收到的错误是
LogicException in Model.php line 2667: Relationship method must return an object of type Illuminate\Database\Eloquent\Relations\Relation
Model.php 第 2667 行中的 LogicException:Relationship 方法必须返回 Illuminate\Database\Eloquent\Relations\Relation 类型的对象
In part of the error tree?? it shows this which is from the Middleware
在错误树的一部分??它显示了来自中间件的这个
at Model->__get('isTeacher') in MustBeTeacherToMakePayment.php line 19
在 Model->__get('isTeacher') 在 MustBeTeacherToMakePayment.php 第 19 行
which is the if statement on the first line above.
这是上面第一行的 if 语句。
Is anyone able to tell me what I'm doing wrong? This is driving me mad
有没有人能告诉我我做错了什么?这让我发疯
回答by jedrzej.kurylo
Instead of calling the isTeacher()function you are accessing isTeacherattribute. Eloquent sees a method of that name and identifies it as a method that should return relation definition. And then you get the error because relation definition methods should return Relationobject.
您正在访问isTeacher属性,而不是调用isTeacher()函数。Eloquent 看到具有该名称的方法并将其标识为应该返回关系定义的方法。然后你会得到错误,因为关系定义方法应该返回Relation对象。
You have to replace
你必须更换
if(!\Auth::user()->isTeacher)
with
和
if(!\Auth::user()->isTeacher())
and the error will be gone.
错误就会消失。