简体   繁体   English

从子关系中获取父 model OOP Laravel

[英]Get parent model from child relationship OOP Laravel

I'm facing an issue with model extension.我遇到了 model 分机的问题。 Here's an example of my problem:这是我的问题的一个例子:

I have a User model and an Admin model that extends my User model. I use a github repo called Bouncer for permissions.我有一个用户 model 和一个扩展我的用户 model 的管理员 model。我使用一个名为 Bouncer 的 github 回购以获得权限。 When I save my roles for an Admin model, it saves as /App/Admin and for Users, it saves as /App/User for the model reference.当我为 Admin model 保存我的角色时,它保存为 /App/Admin,对于 Users,它保存为 /App/User 以供参考 model。

So when I call my roles for a Admin or for a User, no problem.因此,当我将我的角色称为管理员或用户时,没问题。 But my issue is when I want to query all my users with their roles.但我的问题是当我想查询所有用户的角色时。 I obviously get all my users AND my admin, but the Admins can't get their roles because the are "/App/Admin" in the database.我显然得到了我所有的用户和我的管理员,但管理员无法获得他们的角色,因为它们在数据库中是“/App/Admin”。

How can I get all the roles of my "extended" models when I call the parent?当我打电话给父母时,我怎样才能得到我的“扩展”模型的所有角色?

You will create a relationship in your model using belongs to and use a method called "with ()".您将在您的 model 中使用属于并使用名为“with ()”的方法来创建关系。

First step: In your model, create belongs to ex:第一步:在你的model中,创建属于ex:

public function post()
{
    return $this->belongsTo('App\Post', 'foreign_key', 'other_key');
}

Second step: You will use it in your controller,example:第二步:您将在您的 controller 中使用它,例如:

$users = User::with('podcasts')->get();

Eloquent: Relationships https://laravel.com/docs/7.x/eloquent-relationships#updating-belongs-to-relationships Eloquent:关系https://laravel.com/docs/7.x/eloquent-relationships#updating-belongs-to-relationships

Another example Get Specific Columns Using “With()” Function in Laravel Eloquent另一个示例使用“With()”获取特定列 Function in Laravel Eloquent

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM