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
之类的事情时,我会得到空值
我将数据库中车辆的 ID 添加到产品表上的
imageable_id
,并将产品表上的 imageable
类型添加为“车辆”。
我在这里做错了什么?
一切看起来都不错,你应该通过
imageable
访问它:
$product = Product::findOrFail($id);
return $product->imageable;
来自 Laravel 文档:
您还可以从以下位置检索多态关系的所有者: 通过访问执行方法的名称来实现多态模型 对 morphTo 的调用。
在您的情况下,执行对
morphTo
的调用的方法是可想象的。
我认为您在
imageable()
模型中使用 Product
作为方法名称是让您失望的原因......
您需要:
vehicle()
然后你可以像你想要的那样调用 $product->vehicle
或者$product->imageable