默认情况下停止获取用户关系(Laravel)

时间:2020-07-18 09:22:39

标签: php laravel eloquent axios laravel-7

每当我打电话

$user = \App\User::find(Auth::user()->id);
return response()->json($user);

它会返回用户以及相关关系,但我没有要求。

{
 
 "id":51,
 "name":"Admin",
 "username":"administrator",
 "avatar":"1592477660_FB_IMG_15890226824693948.jpg",
 "cover":"1592477660_Goku-Dragon-Ball-Z-1710x900.jpg",
 "gender":"male",
 "posts":[
       {
        "id":19, 
        "body": "this is the body"
       },
       {
        "id":20, 
        "body": "this is the second body"
       },
       {
        "id":21, 
        "body": "this is the third body"
       },
  ]
}

我不想急于加载属于该用户的所有帖子,而这只是默认行为。如果用户有1000多个帖子怎么办?这会变得很混乱。

Post.php

class Post
{   
    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'user_id', 'body',
    ];

    public function user()
    {
        return $this->belongsTo(User::class);
    }
}

User.php

class User
{   
    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'user_id', 'body',
    ];

    public function post()
    {
        return $this->hasMany(Post::class);
    }
}

2 个答案:

答案 0 :(得分:1)

您可以使用makeHidden()方法隐藏不需要的属性和关系。

$user = \App\User::find(Auth::user()->id)->makeHidden('posts');
return response()->json($user);

makeHidden()暂时隐藏属性。如果要永久隐藏所有查询中的属性,则必须像这样将其添加到模型中

namespace App;

use Illuminate\Database\Eloquent\Model;

class User extends Model
{
    /**
     * The attributes that should be hidden for arrays.
     *
     * @var array
     */
    protected $hidden = ['posts'];
}

如果您希望加载帖子,则应在查询中使用makeVisible()方法:

$user = \App\User::where('id', Auth::user()->id)
        ->with('post')
        ->makeVisible('posts')->get()

答案 1 :(得分:0)

您可以使用without方法巫婆专门为此:

$user = \App\User::without('posts')->find(Auth::user()->id);
return response()->json($user);