【问题标题】:morphTo and hasMany LaravelmorphTo 和 hasMany Laravel
【发布时间】:2025-12-06 19:00:02
【问题描述】:

关于 Laravel 中一些数据模型关系的快速查询。

我有一个产品,它属于一个用户,但一个用户可以有很多产品。但是一个产品也可以有很多人对该产品提出报价;

class Product extends Model
{
    public function user(){
        return $this->belongsTo('App\User');
    }
    public function offer(){
        return $this->hasMany('App\Offer');
    }

但是一个产品也可以有不同的产品子类型,例如,一个可能是汽车或手机,在我的迁移中每个都有不同的列,所以我假设我需要变形很多

Product.php

public function imageable()
{
    return $this->morphTo();
}

Vehicle.php

public function products()
{
  return $this->morphMany('App\Product', 'imageable');
}

但是,调用时:

$product = Product::findOrFail($id);

当我尝试执行类似$product->vehicle 之类的操作时,我得到了 null

我将数据库中车辆的 ID 添加到 products 表上的 imageable_id 中,并将 imageable 类型添加到 products 表上的“vehicle”中。

我在这里做错了什么?

【问题讨论】:

    标签: php mysql laravel


    【解决方案1】:

    一切正常,您只需通过imageable 访问它:

    $product = Product::findOrFail($id);
    return $product->imageable;
    

    来自 Laravel documentation:

    您还可以从 多态模型通过访问执行的方法的名称 对 morphTo 的调用。

    在您的情况下,执行对morphTo 的调用的方法是可成像的。

    【讨论】:

    • 这让我更加感谢你,但是我现在得到'Class 'vehicle' not found'
    • 如何将数据存储在多态表中?在数据库中 imageable_type 应该是这样的:App\Vehicle
    • 啊,你是对的,它是数据库中的 App\Vehicle,谢谢 Chase! (当我允许时,我会标记为正确的)
    • 很高兴听到我能提供帮助!
    • 你很快,@chasenyc