Skip to content

Instantly share code, notes, and snippets.

@NandoKstroNet
Last active March 18, 2024 17:02
Show Gist options
  • Save NandoKstroNet/e5151881a1695a34fb7aff9ca3d3fc00 to your computer and use it in GitHub Desktop.
Save NandoKstroNet/e5151881a1695a34fb7aff9ca3d3fc00 to your computer and use it in GitHub Desktop.
FIlament V3 Tenant Driven: Insumos Pedidos Recurso
<?php
//Order Items Migration Fields
$table->foreignId('order_id')
->constrained()
->cascadeOnDelete();
$table->foreignId('product_id')
->constrained()
->cascadeOnDelete();
$table->integer('amount');
$table->integer('order_value');
//Order Factory Definition:
'code' => $this->faker->uuid()
//Order Items Factory Definition:
'amount' => rand(1, 50),
'order_value' => ($this->faker->randomFloat(2, 1, 1000)) * 100 //product price * amount
//Orders Table Seeder Run:
$store = \App\Models\Store::first();
$products = $store->products()->orderByRaw('RANDOM()')->take(5)->get();
$belongsTenantStore = [
'store_id' => $store->id,
'tenant_id' => $store->tenant_id
];
$user = \App\Models\User::factory()
->hasOrders(1, $belongsTenantStore)
->create();
$order = $user->orders->first();
foreach ($products as $prod) {
$amount = rand(1, 5);
$order->items()->create(array_merge([
'product_id' => $prod->id,
'amount' => $amount,
'order_value' => $prod->price * $amount
], $belongsTenantStore));
}
//Order Model Details:
protected $withCount = ['items'];
public function orderTotal(): Attribute
{
return new Attribute(fn ($attr) => $this->items->sum('order_value') / 100);
}
public function items()
{
return $this->hasMany(OrderItem::class);
}
public function user(): BelongsTo
{
return $this->belongsTo(User::class);
}
//Order Items Model Details
public function order(): BelongsTo
{
return $this->belongsTo(Order::class);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment