Laravel Eloquent关系数据隐藏在响应中

时间:2022-10-16 08:29:51

I have two models: User and Group. A user can be a member of just one group, and a group can have multiple users:

我有两个模型:用户和组。用户可以只是一个组的成员,一个组可以有多个用户:

User:

用户:

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class User extends Model
{
    protected $table = 'user';
    protected $primaryKey = 'user_id';

    protected $fillable = [];
    protected $visible = ['user_id', 'name', 'points', 'group_id', 'profile'];


    /**
     * Get group where user belongs to
     */
    public function group()
    {
        return $this->belongsTo('App\Models\Group', 'group_id', 'group_id');
    }
}

Group:

组:

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class Group extends Model
{
    protected $table = 'group';
    protected $primaryKey = 'group_id';

    protected $fillable = [];
    protected $visible = ['group_id', 'name', 'profile'];

    /**
     * Get all group users.
     */
    public function users()
    {
        return $this->hasMany('App\Models\User', 'group_id', 'group_id');
    }
}

Now in my controller, I want to retrieve the user data and the users' group data. Therefore I use this:

现在在我的控制器中,我想检索用户数据和用户的组数据。因此我用这个:

$users = User::with('group')
        ->orderBy('points', 'DESC')
        ->take(50)
        ->get();

return response()->json($users);

So far so good. I expect the above to return something like this:

到现在为止还挺好。我希望上面的内容能够返回:

[
  {
    "user_id": 27,
    "name": "linnie15",
    "points": 18565,
    "group_id": 6,
    "profile": null,
    "group": {
      "group_id": 6,
      "name": "White Wall",
      "profile": "Et tempore voluptatibus sunt ratione ut. Eum sint mollitia omnis eius ut facilis aut. Sed quisquam quis velit qui sint soluta. Autem quia ipsam esse sapiente delectus vel."
    }
  },
]

But, here is the problem. The only thing it returns is this:

但是,这是问题所在。它唯一返回的是:

[
  {
    "user_id": 27,
    "name": "linnie15",
    "points": 18565,
    "group_id": 6,
    "profile": null
  },
]

How is that possible? In fact, I found the solution, by adding 'group' to the $visible array in the User model. But why is that? I mean, should I really add all my relationships to the $visible array? Why would that be necessary. If you query a relationship, you always want the result, isn't it?

怎么可能?实际上,我通过在User模型中的$ visible数组中添加“group”来找到解决方案。但那是为什么呢?我的意思是,我应该将所有关系添加到$ visible数组吗?为什么这是必要的。如果你查询一个关系,你总是想要结果,不是吗?

3 个解决方案

#1


0  

As by seeing your code, the relationship between user and group would be supposed to be like this (you shouldn't give the 3rd argument in hasMany() relationsip):

通过查看代码,用户和组之间的关系应该是这样的(你不应该在hasMany()relationsip中给出第三个参数):

return $this->belongsTo('App\Model\Group', 'group_id');

Same case for method users() in Group model:

组模型中方法用户()的情况相同:

return $this->hasMany('App\Model\User');

According to laravel docs, the hasMany() takes:

根据laravel docs,hasMany()采用:

return $this->hasMany('App\Model', 'foreign_key', 'local_key');

Remember that you must add all the properties in $visible

请记住,您必须在$ visible中添加所有属性

See visibility docs from Laravel

请参阅Laravel的可见性文档

Hope this helps!

希望这可以帮助!

#2


0  

Yes, in your case you must add all your properties in the visible array. If you don't want to do that, use $hidden instead of $visible, and put inside it only the properties that you don't want to be visible in your responses.

是的,在您的情况下,您必须在可见数组中添加所有属性。如果您不想这样做,请使用$ hidden而不是$ visible,并在其中仅包含您不希望在响应中显示的属性。

The same happens with $fillable and $guarded, you must use just one of them.

$ fillable和$ guarded也是如此,你必须只使用其中一个。


EXTRA:

额外:

I would like to add that it's not necessary to do return response()->json($users);. In Laravel 5.3 you can just return $users; and will be automatically returned as a json array.

我想补充一点,没有必要做return response() - > json($ users);.在Laravel 5.3中,您只需返回$ users;并将自动作为json数组返回。

#3


0  

Well sir you have a problem in relations defined. The third parameter should be user_id. Try following code and let me know

先生,您在定义关系时遇到问题。第三个参数应该是user_id。请尝试以下代码并告诉我们

/** * Get group where user belongs to  */ 
public function group() { 
     return $this->belongsTo('App\Models\Group', 'group_id', 'user_id'); 
 }

#1


0  

As by seeing your code, the relationship between user and group would be supposed to be like this (you shouldn't give the 3rd argument in hasMany() relationsip):

通过查看代码,用户和组之间的关系应该是这样的(你不应该在hasMany()relationsip中给出第三个参数):

return $this->belongsTo('App\Model\Group', 'group_id');

Same case for method users() in Group model:

组模型中方法用户()的情况相同:

return $this->hasMany('App\Model\User');

According to laravel docs, the hasMany() takes:

根据laravel docs,hasMany()采用:

return $this->hasMany('App\Model', 'foreign_key', 'local_key');

Remember that you must add all the properties in $visible

请记住,您必须在$ visible中添加所有属性

See visibility docs from Laravel

请参阅Laravel的可见性文档

Hope this helps!

希望这可以帮助!

#2


0  

Yes, in your case you must add all your properties in the visible array. If you don't want to do that, use $hidden instead of $visible, and put inside it only the properties that you don't want to be visible in your responses.

是的,在您的情况下,您必须在可见数组中添加所有属性。如果您不想这样做,请使用$ hidden而不是$ visible,并在其中仅包含您不希望在响应中显示的属性。

The same happens with $fillable and $guarded, you must use just one of them.

$ fillable和$ guarded也是如此,你必须只使用其中一个。


EXTRA:

额外:

I would like to add that it's not necessary to do return response()->json($users);. In Laravel 5.3 you can just return $users; and will be automatically returned as a json array.

我想补充一点,没有必要做return response() - > json($ users);.在Laravel 5.3中,您只需返回$ users;并将自动作为json数组返回。

#3


0  

Well sir you have a problem in relations defined. The third parameter should be user_id. Try following code and let me know

先生,您在定义关系时遇到问题。第三个参数应该是user_id。请尝试以下代码并告诉我们

/** * Get group where user belongs to  */ 
public function group() { 
     return $this->belongsTo('App\Models\Group', 'group_id', 'user_id'); 
 }