Laravel 5.3至5.4关系foreignKey问题 [英] Laravel 5.3 to 5.4 relations foreignKey issue

查看:205
本文介绍了Laravel 5.3至5.4关系foreignKey问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

更新到5.4后,我的关系不再正常工作.经过检查,我发现Laravel现在正在寻找其他 foreignKey名称:user_user_idpost_post_id而不是user_idpost_id等.这一直有效到L 5.3.我还必须将一些数据透视表主键更新为tag_tag_id等,以使它们再次正常工作.

After updating to 5.4, my relations where not working properly anymore. After inspecting I found out Laravel is now looking for different foreignKey names: user_user_id or post_post_id instead of user_id,post_id etc. This was working until L 5.3. I also had to update some of my pivot tabels primarykey to tag_tag_id etc in order to get them working again.

我根据此新约定更新了表的外键名称,现在它可以正常工作了.但是我仍然想知道为什么以及如何改变以及它来自何处.

I updated my tables foreignkey names according to this new convention and now it's working. But I still would like to know why and how this changed and where it's coming from.

谢谢!

推荐答案

您是否使用getKeyName覆盖了模型的主键?

Are you overriding the primary key on your models using getKeyName ?

Laravel仍使用与外键相同的约定user_id.

Laravel still uses the same convention user_id as the foreign key.

但是,在5.4中,定义关系时不需要显式指定外键.

However, in 5.4, you don't need to explicitly specifying the foreign key when defining the relationship.

从文档中

就像以前的Laravel版本一样,这种关系通常使用user_id作为外键.但是,如果您要覆盖User模型的getKeyName方法,则该行为可能与以前的版本不同

Just like previous Laravel releases, this relationship will typically use user_id as the foreign key. However, the behavior could be different from previous releases if you are overriding the getKeyName method of the User model

从5.3升级到5.4.0

更新

该问题也可能是由设置$ primaryKey的值引起的. 您没有提交任何代码.但是,假设在您的用户模型上,您定义了$primaryKey = user_id Laravel会将列名附加到该键名上.因此,您会看到laravel尝试查询user_user_id.

The problem might be caused also by setting the value of $primaryKey. You did not submit any code. However, assuming on your user model, you define $primaryKey = user_id Laravel will append the column name to this key name. Thus, you see laravel trying to query user_user_id.

只需从用户模型中删除$ keyname,laravel将采用遵循user_id约定的外键.

Just remove the $keyname from the user model, and laravel will assume the foreign key following the convention user_id.

或者您可以定义外键,显式地将第二个参数传递给belongsTo(): return $this->belongsTo(User::class, 'user_id);

Or you could define the foreign key explicitly passing a second argument to the belongsTo(): return $this->belongsTo(User::class, 'user_id);

这篇关于Laravel 5.3至5.4关系foreignKey问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆