morphTo 并拥有许多 Laravel

问题描述 投票:0回答:2

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
类型添加为“车辆”。

我在这里做错了什么?

php mysql laravel
2个回答
5
投票

一切看起来都不错,你应该通过

imageable
访问它:

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

来自 Laravel 文档

您还可以从以下位置检索多态关系的所有者: 通过访问执行方法的名称来实现多态模型 对 morphTo 的调用。

在您的情况下,执行对

morphTo
的调用的方法是可想象的。


0
投票

我认为您在

imageable()
模型中使用
Product
作为方法名称是让您失望的原因......

您需要:

  • 将“imageable”方法重命名为
    vehicle()
    然后你可以像你想要的那样调用
    $product->vehicle
    或者
  • 保留名为“imageable”的方法,但实际上通过名称调用该方法:
    $product->imageable
© www.soinside.com 2019 - 2024. All rights reserved.