如果它具有至少一个User,我想获得Section模型的集合。从文档的has()方法可以做到这一点。检索到的集合中没有“用户”关系。但是,当我遍历集合时,我可以获得“用户”的属性。为什么会这样?
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();
收集是这个
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",
},
],
}
现在更奇怪的是,当我在下面执行此操作时,即使在集合中不存在“用户”关系,它也提供了用户的属性。为什么会这样?
@foreach ($section as $section)
@foreach ($section->users as $student)
<p>{{$student->name}}</p>
@endforeach
@endforeach
solomon
uche
kene
第一:
@foreach ($section as $section) //this line, you are using the same name variable.
@foreach ($section->users as $student)
<p>{{$student->name}}</p>
@endforeach
@endforeach
更改为
@foreach ($section as $singleSection)
@foreach ($singleSection->users as $student)
<p>{{$student->name}}</p>
@endforeach
@endforeach
还有您到底想要什么?您是否想要User
?
看起来像您的第一个回声:
$section = Section::where('id' , 1)->has('users')->get();
仅打印它有用户的部分,但您并不是在明确地说也要给我用户。
在下一个循环中,您将循环浏览视图中的每个部分,特别是说循环关系。此行可见:@foreach ($section->users as $student)
我在这里阅读文档:https://laravel.com/docs/6.x/eloquent-relationships#querying-relations
在打印此部分时,在您的第一个回声中,您可以像这样获得用户:echo $section-> users()