Retrieve multiple fields from another model as select

Published 2 years ago by madsynn

Can anyone tell me how i would go about creating the relationship that would allow me to pull multiple fields from one model to another almost like a mirror copy but in a different area of the site.

Explination example:

ProductsModel table fields:

  • name
  • upc
  • price
  • sku
  • barcode

Warehouse Model table fields:

  • name = name from products
  • upc = upc from products
  • price = price from products
  • barcode = barcode from products
primordial

If you want a hasOne relationship I would use an observer to keep them in sync. Laravel supports 16 different events so perhaps you can hook into the "saved" event. For example;

Product Model

    public function warehouse()
    {
        return $this->hasOne('\App\Product');
    }

Warehouse Model You would need to add product_id as a foreign key on the warehouse table.

    public function product()
    {
        return $this->belongsTo('\App\Product');
    }

Then hook into "saved" on the product model to update the value of it's associated warehouse model.

https://laravel.com/docs/5.3/eloquent-relationships

https://bosnadev.com/2014/12/28/laravel-model-observers/

Many ways to skin a cat.

Please sign in or create an account to participate in this conversation.