简体   繁体   English

在Laravel模型中建立新的自定义关联方法

[英]Making new custom relation method in laravel model

I am using this for my api when i visit someone profile: 访问某人的个人资料时,我将其用于我的api:

return response()->
json(
    User::load(["posts.comments"])
    ->where('username', request('username'))
    ->firstOrFail()
);

Now when I want to use paginate on relation I do it like this: 现在,当我想在关系上使用分页时,我会像这样:

$user->posts()->paginate(10);

But I need relation so I found: 但是我需要联系,所以我发现:

$user->setRelation('posts', $user->posts()->paginate(10));

Now I am wondering is there a way to create custom relation method inside model so when I use load(['posts.comments']) it returns that custom relations? 现在我想知道是否有一种方法可以在模型内部创建自定义关系方法,因此当我使用load(['posts.comments'])它会返回该自定义关系吗?

One way is to do this: 一种方法是执行此操作:

return response()->
json(
    User::with(['posts' => function($q) {
        $q->paginate(5);
    }, 'posts.comments' => function($q) {
        $q->paginate(5, ['*'], 'commentsPage', request('commentsPage'));
    }])
    ->where('username', request('username'))
    ->firstOrFail()
);

Although I am not sure how to pass $q->nextPageUrl() 虽然我不确定如何传递$q->nextPageUrl()

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

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