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

Categories

0 votes
804 views
in Technique[技术] by (71.8m points)

eloquent - Laravel 8 Using Belongs To Failing When Using Where

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...