Laravel的morphOne / morphTo返回null

时间:2019-06-11 16:46:08

标签: laravel eloquent

我正在尝试为一种产品显示多张图像。 我尝试创建常规的hasMany / belongsTo关系,但是我的查询为属于它的每个图像重复了产品。因此,我决定使用morphOne多态关系。我在这里和整个Google上都读了很多问题/答案,却找不到我的答案,或者也许我只是不了解一切如何工作。

在Laravels文档之后,我有以下内容:

Product model

    public function images()
    {
        return $this->morphOne(Image::class, 'imageable');
    }

Image model

    protected $fillable = [
        'image', 'imageable_id', 'imageable_type'
    ];

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

Image migration

        Schema::create('images', function (Blueprint $table) {
            $table->increments('id');
            $table->string('image')->nullable();
            $table->integer('imageable_id')->unsigned();
            $table->string('imageable_type');
            $table->timestamps();
        });

Database image

https://ibb.co/bd8VsCK

Image Factory

    $noteable = App\Image::class;

    return [
        'image' =>$faker>image(storage_path('app/public/products'),400,300,'',false), 
        'imageable_type' => $noteable,
        'imageable_id' => $faker->numberBetween(1,20),
    ];

也许我缺少一些东西,或者这种方法不适合我想要的。我对Laravel来说还很陌生,所以任何帮助都会很棒。谢谢!

1 个答案:

答案 0 :(得分:0)

我认为这是您要实现的非常复杂的解决方案。我之前在我的项目上所做的就是有两个表,因此有两个php模型,一个是Product.php和ProductItem.php(图片);

class Product extends Model 
{
    protected $guarded = [];

    public function images() {
        return $this->hasMany(ProductImage::class);
    }

}

class ProductItem extends Model 
{
    protected $guarded = [];
}

在控制器方法上,查询产品的方式将是

public function index() 
{
    $products = Product::with('images')->get();
}

您的数据库架构为

products table 
    - name
    - id
    - ....

product_items table
    - id
    - product_id
    - path or image or name