【问题标题】:Exception Property [ ] does not exist on this collection instance此集合实例上不存在异常属性 []
【发布时间】:2020-09-25 15:40:14
【问题描述】:

我正在尝试获取参加考试的学生的 ID。我在 Laravel 中使用关系,但我不知道我错过了什么。这是代码:

我的模型

考试模式:

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


    public function professor()
    {
        return $this->belongsTo(Professor::class,'prof_id');
    }

    public function questions()
    {
        return $this->hasMany(Question::class);
    }

    public function examen_passers()
    {
        return $this->hasMany(Examen_passer::class);
    }
}

考试模式:

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

    public function examen()
    {
        return $this->belongsTo(Examen::class);
    }

    public function reponses()
    {
        return $this->hasMany(Reponse::class);
    }

      public function reponsestxt()
    {
        return $this->hasMany(Reponsetxt::class);
    }
}

我的控制器:

public function corriger()
    {
 $examen = Examen::where('prof_id',Auth::guard('professor')->id())->get();
 dd($examen->examen_passers->etudiant_id);

}

【问题讨论】:

  • 甚至使用:foreach($examen as $examen) { echo $examen->examen_passers->etudiant_id; }
  • $examen 的输出是一个集合,您不能在该集合上调用examen_passers 函数,请使用first() 而不是get()
  • 谢谢!现在我明白了。
  • 不客气,但请注意,首先将返回一条记录,如果您需要所有记录继续使用 get 但随后您必须循环输出以获取 etudiant_id,这是一种方法,您还有其他方法(急切加载,...),具体取决于您要实现的目标

标签: php laravel relationship laravel-6


【解决方案1】:

使用pluck() 从您的路人集合中获取所有ID:

$examen->examen_passers->pluck('etudiant_id');

此方法将从集合中的每个项目中获取 etudiant_id 的值,并将它们一起返回到一个数组中。

【讨论】:

    猜你喜欢
    • 2019-06-21
    • 2021-11-19
    • 1970-01-01
    • 1970-01-01
    • 2020-11-12
    • 2019-03-23
    • 2020-07-11
    • 2017-05-12
    • 2018-10-12
    相关资源
    最近更新 更多