鍍金池/ 問答/PHP/ laravel的modelFactory 生成假數(shù)據(jù)時(shí),如何保證不重復(fù)

laravel的modelFactory 生成假數(shù)據(jù)時(shí),如何保證不重復(fù)

問題描述

laravel的modelFactory 生成假數(shù)據(jù)時(shí),如何保證不重復(fù)?

問題出現(xiàn)的環(huán)境背景及自己嘗試過哪些方法

通過unique過濾,但是沒起作用,谷歌了相關(guān)問題,沒有發(fā)現(xiàn)合適的

相關(guān)代碼

use Faker\Generator as Faker;

$factory->define(App\Models\Tab::class, function (Faker $faker) {

    return [
        'name' => $faker->unique()->randomElement(['我的', '搜索', '推薦', '電影', '電視劇', '綜藝', '小品', '動(dòng)漫', '動(dòng)畫屋', '應(yīng)用', '其他']),
        'name_cover' => 'http://imgbftv.b0.upaiyun.com/1342/20180515151342_1_45727.jpeg',
        'name_cover_focus' => 'http://imgbftv.b0.upaiyun.com/1342/20180515151342_1_45727.jpeg',
        'bg_cover' => 'http://imgbftv.b0.upaiyun.com/1342/20180515151342_1_45727.jpeg',
        'operate_type' => $faker->randomElement([0, 1, 2]),
        'status' => $faker->randomElement([0, 1, 2]),
        'operator' => $faker->username,
        'sort' => $faker->unique()->randomDigit,
    ];
});

public function run()
{
    // create tabs and save them to the database
    $tabs = factory(App\Models\Tab::class,8)->create();
}
    

你期待的結(jié)果是什么?實(shí)際看到的錯(cuò)誤信息又是什么?

期待生成的某些字段數(shù)據(jù)是不重復(fù)的,但目前的結(jié)果是有重復(fù)數(shù)據(jù)的

回答
編輯回答
骨殘心

......我覺得應(yīng)該是插件有什么bug,真是無語,我把create換成make,之后又換回來,就自己無緣無故的又好了

2018年3月20日 17:20
編輯回答
浪婳

說個(gè)笨辦法吧。。

定義一個(gè)假數(shù)據(jù)文字?jǐn)?shù)組aTextContent,然后接口方法加個(gè)列表長度參數(shù)listLength,比如列表長度為10,把0~9的數(shù)字插入到一個(gè)新的數(shù)組aRandom,插入順序打亂。

返回假數(shù)據(jù)的時(shí)候就返回 for(int i=0; i<listLength; i++) ...aTextContent[aRandom[i]] (偽代碼)

2017年5月6日 00:04