Laravel可以和belongsToMany一起使用吗? [英] Can Laravel hasOne be used with belongsToMany?

查看:609
本文介绍了Laravel可以和belongsToMany一起使用吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有两个表:



用户:id,name,country_id



国家:id,名称



当然每个 user 只能有一个国家/地区,但每个国家/地区 code>用户。



所以有一个用户使用 hasOne 国家使用的模型的模型belongsToMany 方法?



文档使其看起来像你不能混合和匹配不同类型的关系。

解决方案

你所描述的是一个一对多关系,一个国家有很多用户。您的国家/地区模型应使用 hasMany 关系,而您的用户将拥有 belongsTo 关系。


Let's say I have two tables:

Users: id, name, country_id

Countries: id, name

Of course each user can only have one country, but each country is assigned to multiple users.

So would it be safe to have a User model that utilizes hasOne and a Country model that uses belongsToMany method?

Documentation makes it seem like you can't mix and match different types of relationships.

解决方案

What you are describing is actually a One To Many relationship, where one country has many users. Your Country model should utilize a hasMany relationship, while your user would have a belongsTo relationship.

这篇关于Laravel可以和belongsToMany一起使用吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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