【问题标题】:Get parent relation of an object dynamically in Laravel / Eloquent在 Laravel / Eloquent 中动态获取对象的父关系
【发布时间】:2026-01-12 23:15:02
【问题描述】:

我有三个模型

产品、变体和选项。

class Product {
    public $id;

    public function variants(): HasMany
    {
        return $this->hasMany(Variant::class);
    }
}

class Variant {
    public $id;
    public $product_id;

    public function product(): BelongsTo
    {
        return $this->belongsTo(Product::class);
    }

    public function options(): HasMany
    {
        return $this->hasMany(Option::class);
    }
}  

class Option {
    public $id;
    public $variant_id;

    public function variant(): BelongsTo
    {
        return $this->belongsTo(Variant::class);
    }
} 

我想知道是否有办法让 Variant 的实例获得父(产品)关系和 Option 父(Variant)关系与一行代码。有没有像下面这样的?

$instance->parent(); 

我想避免写作

If (get_class($instance) === 'Variant' ) {
    $instance->product();
} else if (get_class($instance) === 'Option' ) {
    $instance->variant();
} 

【问题讨论】:

    标签: laravel eloquent


    【解决方案1】:

    您可以轻松获得关系模型。喜欢-

    $variants = \App\Models\Variant::latest()->get();
    foreach($variants as $variant)
    {
       $product_name = $variant->product->name; // this will be the product name that that related with this variant
    }
    

    它也适用于单个收藏

    $variant = \App\Models\Variant::find(1)>-first();
    $variant->product;// this is product model instance that related to variant
    

    【讨论】:

    • 感谢您的回答,但这不是我想要的。