How can I handle this type of relationship in Eloquent de Laravel?

1

I know how to handle relationships like "One to Many" but when creating a new sale, what would be the best practice using Eloquent to save?

    
asked by Gregori Piñeres 17.01.2018 в 15:03
source

1 answer

1

In Client.php

/**
 * @return belongsToMany
 */
public function products()
{
    return $this->belongsToMany(Product::class, 'ventas', 'client_id', 'products_id')->withPivot('id','date');
}

/**
 * @return hasMany
 */
public function ventas()
{
    return $this->hasMany(Venta::class, 'client_id');
}

In Product.php

/**
 * @return belongsToMany
 */
public function clients()
{
    return $this->belongsToMany(Client::class, 'ventas', 'products_id', 'client_id')->withPivot('id','date');
}

/**
 * @return hasMany
 */
public function ventas()
{
    return $this->hasMany(Venta::class, 'products_id');
}

On Sale.php

/**
 * @return belongsTo
 */
public function clients()
{
    return $this->belongsTo(Client::class, 'client_id', 'id');
}

/**
 * @return belongsTo
 */
public function products()
{
    return $this->belongsTo(Product::class, 'products_id', 'id');
}

The above are the relationships of the model you show in your image, my answer is, use the relationships you need. According to your model, the sale of a product can be registered as follows:

$client = Client::findOrFail($request->user_id);
$client->products()->syncWithOutDetaching([
    $product_id => [
        'date' => Carbon::now,
    ]
]);
    
answered by 21.01.2018 / 14:00
source