MorphTo and hasMany Laravel

A quick query regarding some data model relationships in Laravel.

I have a product owned by the user, but the user can have many products. But a product can also have many people making an offer on this product, so

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

But the product may also have different subtypes of the product, for example, there may be a car or a mobile phone, each with different columns in my migration, so I assume that I need to change many

IN Product.php

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

IN Vehicle.php

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

However, when called:

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

I get null when I try to do something like $product->vehicle

I will add the vehicle identifier to my database imageable_idin the product table, and the type imageableto "vehicle" in the product table.

What am I doing wrong here?

+6
1

, imageable:

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

Laravel :

, morphTo.

, morphTo, .

+5

Source: https://habr.com/ru/post/1017139/


All Articles