Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I know this is me being dumb and not understanding the documentation but I am trying to use the belongsTo feature to access the parent of a class

In the model I have the function defined

class Child extends Model {

    use HasFactory;

    protected $fillable = ['childField'];

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

}

But I am getting an error when trying to retrieve it in a controller

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

The where is working because it's returning the right child but I'm getting an error saying that Property [parent] does not exist when trying to get the parent, what am I missing?

question from:https://stackoverflow.com/questions/65646684/laravel-8-using-belongs-to-failing-when-using-where

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
1.1k views
Welcome To Ask or Share your Answers For Others

1 Answer

In your code, $child is a Collection, not a Model. It should be:

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...