laravel:模型中的函数必须返回一个关系实例

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/47727381/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-08 17:51:13  来源:igfitidea点击:

laravel: function in model must return a relationship instance

laravellaravel-5.5

提问by Ali

I try to build a path for a model on laravel

我尝试在 Laravel 上为模型构建路径

I created a function in my model:

我在我的模型中创建了一个函数:

public function path()
{
    return App\Helper\GeneralController::getURL($this);
}

with dd(App\Helper\GeneralController::getURL($this))test I got the right answer. (output is a URL)

通过dd(App\Helper\GeneralController::getURL($this))测试,我得到了正确的答案。(输出是一个 URL)

but in view with the call: $article->pathI get this error:

但鉴于电话:$article->path我收到此错误:

App\Article:: path must return a relationship instance.
App\Article:: path must return a relationship instance.

What is wrong?

怎么了?

回答by Alexey Mezenin

You need to call it:

你需要调用它:

$article->path()

When you do $article->path, you're trying to use Eloquent relationship which you don't have.

当您这样做时$article->path,您正在尝试使用您没有的 Eloquent 关系。

回答by Ali

I faced that error when I forgot to write returnbefore relation in the model!
check it out now!

当我忘记在模型中的关系之前写返回时,我遇到了那个错误!
现在就去看看!

回答by pwyg

I know this has already been answered and accepted. However, if the OP did want to use a property accessor rather than a method use the "get{property name}Attribute" syntax of Laravel to create a custom attribute.

我知道这已经得到了回答和接受。但是,如果 OP 确实想使用属性访问器而不是方法,请使用 Laravel 的“get{property name}Attribute”语法来创建自定义属性。

Here is what it would look like for this specific case:

下面是这个特定案例的样子:

public function getPathAttribute()
{
    return App\Helper\GeneralController::getURL($this);
}

using this approach "path" can now be called as an attribute and will not be resolved to a relationship using the syntax:

使用这种方法,“路径”现在可以作为属性调用,并且不会使用以下语法解析为关系:

$article->path;

回答by jynk

You're calling a relationship.

你称之为关系。

$article->path

To call the method, use '()', like so,

要调用该方法,请使用“()”,如下所示,

$article->path()

回答by Niklesh Raut

path()is method not object element you need to call as method

path()是方法不是您需要作为方法调用的对象元素

$article->path();