【问题标题】:Change on laravel collection does not effect更改 laravel 集合不影响
【发布时间】:2015-12-04 01:26:09
【问题描述】:

我有一个用户模型,它有一个帖子集合。 我想用他们的帖子返回一组用户数据,除了每个用户的特殊帖子作为 json;为此,我使用此代码:

$users=User::with('posts')->get();
foreach($users as $user){
    $user->posts=$user->posts->except($except_id);
    // $user->posts=null;// ->>> also this code does not work
}
return $users;

但在输出用户的帖子没有改变!!!

已编辑:

$except_id = $user->golden_post_id;

【问题讨论】:

    标签: php laravel collections model eloquent


    【解决方案1】:

    我尝试了一些方法,最后发现unset()可以解决问题。

    此代码有效:

    $users=User::with('posts')->get();
    foreach($users as $user){
        $posts=$user->posts->except($except_id);
        unset($user->posts);
        $user->posts=$post;
    }
    return $users;
    

    【讨论】:

      【解决方案2】:

      您可能应该将其作为 with 调用中的查询约束来代替,例如像这样:

      $users = User::with(['posts' => function($query) use ($except_id) {
          $query->where('id', '!=', $except_id);
      }])->get();
      

      现在您可以获得除 id 为 $except_id 的帖子之外的所有用户的所有帖子,并且您无需在事后对其进行整理。

      【讨论】:

      • 谢谢。但$except_id 来自用户模型($except_id = $user->golden_post_id)。有办法吗?
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-04-11
      • 1970-01-01
      • 2016-04-28
      • 2010-10-12
      • 2023-03-03
      • 2018-12-16
      相关资源
      最近更新 更多