首页 > 解决方案 > laravel eloquent 'has' 方法的行为出人意料

问题描述

如果 Section 模型至少有一个,我想获得它的集合User。从文档中,该has()方法可以做到这一点,太好了。检索到的集合中没有users关系。然而,当我遍历集合时,我可以获得users. 为什么?

class Section extends Model
{
    protected $guarded = [];

    public function users()
    {
        return $this->hasMany('App\User');
    }
}
class User extends Authenticatable
{
    protected $guarded = [];

    public function section()
    {
        return $this->belongsTo('App\Section');
    }
}

我所做的是:

$section = Section::where('id' , 1)->has('users')->get();

集合是这样的:

Illuminate\Database\Eloquent\Collection {#3025
     all: [
       App\Section {#3015
         id: 1,
         class_id: 1,
         section_name: "A",
         created_at: "2019-12-14 18:26:01",
         updated_at: "2019-12-14 18:26:01",
       },
     ],
   }

现在奇怪的是,当我执行以下操作时,即使在集合users中不存在关系,它也会给出用户的属性。

为什么?

 @foreach ($section as $section)
   @foreach ($section->users as $student)
     <p>{{$student->name}}</p>
   @endforeach
@endforeach
solomon
uche
kene

标签: laraveleloquentlaravel-5.8

解决方案


好的,现在我明白你的问题了。

  1. 第一的

has方法并不意味着它将包含User. 这意味着这将返回所有sections至少有一个用户的人。我认为有/有Sectionid ===1 的用户。因此,无论有没有它,在您的代码has中都没有任何区别。

如果要显式加载关系,则应使用with

Section::where('id' , 1)->with('users')->get();. 然后你应该在每个部分下收集用户。

  1. 第二

    您仍然可以访问blade文件中的用户属性的原因是lazy loading. 即使它不包含在原始数据库查询和结果中,但是当您尝试访问它时,laravel 仍然会尝试为您获取它们。这可能会导致 N+1 问题。


推荐阅读