Laravel 8 Using Belongs To Failed When Using Where

Laravel 8 Using Belongs To Failing When Using Where

我知道这是我的愚蠢,不理解文档,但我正在尝试使用 belongsTo 功能访问 class

的 parent

在模型中我定义了函数

class Child extends Model {

    use HasFactory;

    protected $fillable = ['childField'];

    public function parent() {
        return $this->belongsTo(Parent::class, 'parent_id');
    }

}

但是当我尝试在控制器中检索它时出现错误

$child = Child::where('childField', 'ChildTest01')->get();
$parent = $child->parent->parentField;

where 正在工作,因为它返回正确的 child 但我收到一条错误消息,说 Property [parent] does not exist 在尝试获取 parent 时,我错过了什么?

在您的代码中,$childCollection,而不是 Model。应该是:

$child = Child::where('childField', 'ChildTest01')->first();
$parent = $child->parent->parentField;