doumu8217 2017-05-05 18:12
浏览 55
已采纳

雄辩的关系,模型的链接(Laravel 5.4)

I'm kinda confused how the eloquent relationships works in Laravel 5.4. I got a school model that has a "hasMany" relationship with my user model:

public function users()
{
    return $this->hasMany('App\User');
}

The user is not required to be linked to a school though, so I haven't put the belongsTo (school) function on my user model.

How should I link the user to a school, when I create the user and how can I pull all users in a specific school into a view, for example?

  • 写回答

1条回答 默认 最新

  • duanji7182 2017-05-05 19:27
    关注

    If the user can only belong to one school, the most straightforward approach would be to add a school_id column to the users table. Since it's not required, you can allow for it to be null. This will allow you to run $school->users to retrieve a list of users for a given school.

    I would also recommend adding the belongsTo relationship to the User model, so you can do $user->school to retrieve a user's school when applicable. It's okay that it'll be null for some users.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 2024-五一综合模拟赛
  • ¥15 下图接收小电路,谁知道原理
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度
  • ¥30 关于#r语言#的问题:如何对R语言中mfgarch包中构建的garch-midas模型进行样本内长期波动率预测和样本外长期波动率预测
  • ¥15 ETLCloud 处理json多层级问题
  • ¥15 matlab中使用gurobi时报错
  • ¥15 这个主板怎么能扩出一两个sata口
  • ¥15 不是,这到底错哪儿了😭