【发布时间】: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”中。
我在这里做错了什么?
【问题讨论】: