dongzhouji4021 2019-04-07 15:27
浏览 51

如何隐藏Eloquent模型上的关系

I'm struggling with an Eloquent dummy issue. I have a model User which has a many to many relation with a model Like.

I'm getting my user model by its id with:

$likedUser = User::findorfail($user_id);

At some point in the code, I'm doing:

if ($likedUser->likes->where(...)->count()) {
...
}

Then, I want to return my $likedUser WITHOUT the likes (added in the IF condition above by Laravel). How can I do that? If I do that, it does not work:

 return response()->json([
      'is_matched' => $isMatched,
      'liked_user' => $likedUser,
 ], 200);

I would love to have a $likedUser->without('likes') to remove the relation added by Laravel. I tried to $outputUser = $likedUser->replicate() but the unique field of my models disappears..

1) What's the elegant way of only returning my User model without its relationship?

2) Why is Laravel adding the relation even if I never set my variable but only use it in a IF?

Thanks a lot for your time guys!

  • 写回答

0条回答 默认 最新

    报告相同问题?

    悬赏问题

    • ¥15 想问一下树莓派接上显示屏后出现如图所示画面,是什么问题导致的
    • ¥100 嵌入式系统基于PIC16F882和热敏电阻的数字温度计
    • ¥15 cmd cl 0x000007b
    • ¥20 BAPI_PR_CHANGE how to add account assignment information for service line
    • ¥500 火焰左右视图、视差(基于双目相机)
    • ¥100 set_link_state
    • ¥15 虚幻5 UE美术毛发渲染
    • ¥15 CVRP 图论 物流运输优化
    • ¥15 Tableau online 嵌入ppt失败
    • ¥100 支付宝网页转账系统不识别账号