In my definition method I got this:
$users = []; // List of user's ids
$items = []; // List of Item's ids
return [
'user' => $this->faker->randomElement($user),
'item'=> $this->faker->randomElement($item),
];
This makes duplicated rows, (multiple rows with same user column and item column).
e.g: my databse
0: {id:'1',user:'1',item:'1'}
1: {id:'2',user:'5',item:'4'}
2: {id:'3',user:'7',item:'12'}
3: {id:'4',user:'1',item:'3'}
4: {id:'5',user:'1',item:'1'} // Duplicated
5: {id:'6',user:'10',item:'11'}
How can I make this to be unique? (Just one row with unique user and item)
Thanks.
CodePudding user response:
I think the most pragmatic approach is simply to do this outside of the factory. While manually assigning the value to each factory creation.
foreach ($users as $userId) {
foreach ($items as $itemId) {
factory(YourModel::class)->create(
[
'user' => $userId,
'item'=> $itemId,
]
);
}
}
CodePudding user response:
It's all about Combination
$combinations = [];
foreach ($users as $userId) {
foreach ($items as $itemId) {
$combinations[] = [
'user' => $userId, 'item' => $itemId
];
}
}
return $this->faker->randomElement($combinations);