Bvanhaastrecht
4 months ago

Multiple levels down

Posted 4 months ago by Bvanhaastrecht

Hello,

I'm bumping my head over the following:

DB structure:

customer (the customers table)
  id

customer_products (customer can have multiple entries to determine which products are enabled)
  id
  product
  customer
  enabled

products (the products table)
  id
  name
class Customers extends Model
{
    public function products()
    {
        return $this->hasMany('App\Models\CustomerProducts', 'customer');
    }
}

class CustomerProducts extends Model
{
    public function product()
    {
        return $this->belongsTo('App\Models\Products', 'product', 'id');
    }
}

$customer = \App\Models\Customers::with(['products'])
            ->where('id', 1)
            ->first();

I can get the products, but the product itself doens't cary the nested product table info like 'name'.

I can successfully do:

$CustomerProducts = \App\Models\CustomerProducts::with('product')
            ->where('customer', 1)
            ->get();

Tried:

$customer = \App\Models\Customers::with(['products', 'product'])
            ->where('id', 1)
            ->first();

But this fails because 'product' cant be found.

How can I get the nested product details thru the 'customer'?

Kind regards, Bastiaan

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