php Eloquent - 调用未定义的关系

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

Eloquent - Call to undefined relationship

phplaraveleloquentmany-to-manyrelationship

提问by Kieran Chadwick

I have a userstable and a permissionstable. It's a many-to-many relationship so I also have a users_permissionstable with a user_id& module_permission_idcolumn.

我有一个用户表和一个权限表。这是一个多对多的关系,所以我还有一个带有user_idmodule_permission_id列的users_permissions表。

The user model has the following relationship:

用户模型有如下关系:

public function permissions()
{
    return $this->belongsToMany(Permission::class, 'users_permissions', 'user_id', 'module_permission_id');
}

When I run my query, the result contains an empty permissions array.

当我运行查询时,结果包含一个空的权限数组。

User::with('permissions');

If I echo the query in the with, I get the error: Call to undefined relationship [] on model [App\Models\User]

如果我在 with 中回显查询,则会收到错误消息:调用模型 [App\Models\User] 上的未定义关系 []

User::with(['permissions', function($q) {
            echo $q->toSql();  
            die();
        }]);

The rest of the query works, it's just trying to get permissions which is failing.

查询的其余部分有效,它只是尝试获取失败的权限。

回答by vincentLg

Maybe you just forgot the ->get() after User::with('permissions')->get() ?

也许你只是忘记了 User::with('permissions')->get() 之后的 ->get() ?

https://laravel.com/docs/5.0/eloquent#eager-loading

https://laravel.com/docs/5.0/eloquent#eager-loading

回答by PHZ.fi-Pharazon

In my case it was a coding convention issue related to camelCase vs. snake_case: In the Model there was

在我的情况下,这是一个与camelCase vs. snake_case相关的编码约定问题:在模型中有

public function getPermissions()

and in the query there was

在查询中有

User::with(['get_permissions'])

When I changed this to

当我把它改成

User::with(['getPermissions'])

it started to work, although I'd say the Laravel way would be to use snake_case instead.

它开始工作了,虽然我会说 Laravel 的方式是使用 snake_case 代替。

This confused me for a couple of days since frameworks like Symfony and AngularJs has a mixed conventions that somewhere you need to write parameters in snake_case and somewhere else in camelCase. I didn't find any documentation on Laravel site how they handle this, so I tried it the Straight Way and it seemed to be the case here :)

这让我困惑了几天,因为像 Symfony 和 AngularJs 这样的框架有一个混合的约定,你需要在蛇的某处写参数,而在 camelCase 的其他地方。我没有在 Laravel 网站上找到任何他们如何处理这个问题的文档,所以我尝试了直接方式,这里似乎就是这种情况:)