【问题标题】:Why doesn't the Collections method 'contains' work if the collection has relations?如果集合有关系,为什么集合方法“包含”不起作用?
【发布时间】:2017-09-18 21:31:00
【问题描述】:

例如:

$users = User::all();

$user = User::find(1)->get();

$sameUser = User::find(1)->with('roles')->get();

$user->is($sameUser) // true

$users->contains($user) // true

$users->contains($sameUser) // false

不应该对所有三个检查都返回 true 吗?

【问题讨论】:

    标签: laravel collections contains


    【解决方案1】:

    这并不是说它不适合这种关系,而是你正在用get() 电话搞砸事情。 find() 返回用户实例并在后台实际调用 User::where('id', '=', $id)->first();,因此以下所有内容都将返回 true:

    $users = User::all();
    
    $user = User::find(1);
    
    $sameUser = User::with('roles')->find(1);
    
    $user->is($sameUser) 
    
    $users->contains($user)
    
    $users->contains($sameUser)
    

    【讨论】:

    【解决方案2】:

    https://github.com/laravel/framework/issues/18902

    从技术上讲,如果一个已经预先加载的对象是不一样的 关系,而另一个没有。虽然他们可能代表 数据库中的同一行,PHP 无法知道。

    在这种情况下,您可能需要根据主键进行操作。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-08-11
      • 2013-03-20
      • 2012-01-24
      • 1970-01-01
      • 2012-05-25
      • 1970-01-01
      • 2012-11-30
      • 1970-01-01
      相关资源
      最近更新 更多