【问题标题】:ErrorException in HasRelationships.phpHasRelationships.php 中的 ErrorException
【发布时间】:2017-10-12 02:31:58
【问题描述】:

我收到此错误,但我不确定是因为关系还是其他原因?

错误

ErrorException in HasRelationships.php line 487:
Class 'Company' not found 

用户.php

public function company(){ $this->belongsTo('Company', 'user_id'); }

公司.php

public function user(){ $this->belongsTo('User') ; }

现在我的目标是隐藏导航栏中的“创建列表”按钮,如果用户与公司表没有关系。我知道我可以使用角色或中间件来实现,但我的朋友给我发了类似的东西并告诉我这样做更容易。

if(count($user->company) > 0) 

所以现在我正在尝试找出方法,但仍然无法弄清楚如何修复错误。

导航视图

@inject('user', 'App\User')
   @if(count($user->company) > 0)
     <li><a href="{{route('listings.create', [$area])}}">Add listing</a></li>
   @endif

///更新

它没有找到类“公司”,因为我没有在我的关系中使用完整的命名空间,但现在我收到了这个新错误。

错误

ErrorException in HasAttributes.php line 403:
Relationship method must return an object of type Illuminate\Database\Eloquent\Relations\Relation 

(View: /Users/username/Desktop/laravel/resources/views/layouts/partials/_navigation.blade.php) 
(View: /Users/username/Desktop/laravel/resources/views/layouts/partials/_navigation.blade.php) 
(View: /Users/username/Desktop/laravel/resources/views/layouts/partials/_navigation.blade.php)

【问题讨论】:

    标签: php laravel eloquent relationship


    【解决方案1】:

    在关系代码中使用完整的命名空间:

    public function company()
    {
        return $this->belongsTo('App\Company', 'user_id');
    }
    

    【讨论】:

    • 好吧,有些东西改变了,但现在我得到了这个Relationship method must return an object of type Illuminate\Database\Eloquent\Relations\Relation
    • 谢谢,完整的命名空间解决了这个问题,我更新了主题。
    猜你喜欢
    • 2023-03-04
    • 2015-05-24
    • 1970-01-01
    • 2017-10-29
    • 1970-01-01
    • 1970-01-01
    • 2017-10-23
    • 2019-10-17
    • 2018-06-28
    相关资源
    最近更新 更多