你好,我正在为打折模式创建一个工厂。我有两个字段('original_price‘和'discounted_price')。我在工厂中使用randomFloat为‘原始_价格’创建一个带有2个小数的随机数。如何将“discounted_price”设置为总是比“原始价格”更低的值?
目前,'discounted_price‘具有与'original_price’相同的假值,因为我找不到这样的方法。
<?php
namespace Database\Factories;
use App\Models\Category;
use App\Models\User;
use Illuminate\Database\Eloquent\Factories\Factory;
/**
* @extends \Illuminate\Database\Eloquent\Factories\Factory<\App\Models\Discount>
*/
class DiscountFactory extends Factory
{
/**
* Define the model's default state.
*
* @return array<string, mixed>
*/
public function definition()
{
return [
'user_id' =>User::factory(),
'category_id' => Category::factory(),
'title' => $this->faker->sentence(),
'slug' => $this->faker->slug(),
'body' => '<p>' . implode('</p><p>', $this->faker->paragraphs(6)) . '</p>',
'original_price' => $this->faker->randomFloat('2',0,2),
'discounted_price' => $this->faker->randomFloat('2',0,2),
];
}
}我想我找到了一个解决方案,但我不知道这样做是否正确。我的想法是'discounted_price‘的最小值应该是'original_price’的50%,最大值应该是'original_price‘- 5。这是正确的方法吗?
<?php
namespace Database\Factories;
use App\Models\Category;
use App\Models\User;
use Illuminate\Database\Eloquent\Factories\Factory;
/**
* @extends \Illuminate\Database\Eloquent\Factories\Factory<\App\Models\Discount>
*/
class DiscountFactory extends Factory
{
/**
* Define the model's default state.
*
* @return array<string, mixed>
*/
public function definition()
{
return [
'user_id' =>User::factory(),
'category_id' => Category::factory(),
'title' => $this->faker->sentence(),
'slug' => $this->faker->slug(),
'body' => '<p>' . implode('</p><p>', $this->faker->paragraphs(6)) . '</p>',
$original_price = 'original_price' => $this->faker->randomFloat('2',0,2),
'discounted_price' => $this->faker->numberBetween($min=$original_price/2, $max=$original_price-5)
];
}
}发布于 2022-05-20 12:02:35
似乎是正确的,我建议您不要在数组值中混合和匹配属性赋值,以保持清楚。
public function definition()
{
$originalPrice = $this->faker->randomFloat('2', 0, 2);
$discountMin = $originalPrice / 2;
$discountMax = $originalPrice - 5;
return [
'user_id' =>User::factory(),
'category_id' => Category::factory(),
'title' => $this->faker->sentence(),
'slug' => $this->faker->slug(),
'body' => '<p>' . implode('</p><p>', $this->faker->paragraphs(6)) . '</p>',
'original_price' => $originalPrice,
'discounted_price' => $this->faker->numberBetween($discountMin, $discountMax)
];
}https://stackoverflow.com/questions/72312076
复制相似问题