How to take all the words in one normal array from the database in the Laravel framework with a minimum waste of time?

别说谁变了你拦得住时间么 提交于 2019-12-03 17:26:32

You can accomplish inserting unique words into the database entirely inside of MySQL, this should always be faster than pulling all the words into memory, diffing them and sending in the unique values.

To do this you need to add a unique index on your words column. (ref: https://dev.mysql.com/doc/refman/5.7/en/create-index.html)

CREATE UNIQUE INDEX `idx_word` ON `db`.`words` (word);

Then on your insert you need to add ON DUPLICATE KEY (Laravel query builder does not support on duplicate key - can use raw to insert) ref: https://dev.mysql.com/doc/refman/5.7/en/insert-on-duplicate.html, https://laravel.com/docs/5.5/queries#raw-expressions

INSERT INTO word VALUES ('foo'),('bar') ON DUPLICATE KEY word = VALUES(word);

I would use on duplicate key rather than insert ignore. I think insert ignore may hide other potential issues unrelated to duplicate key.

You can get diff two array in Laravel 5.5 so:

$words = DB::table('words')->pluck('word')->toArray(); // Collection converted to simple array

And you can use default function in php for get diff arrays:

$result = array_diff($input_default_array, $words);
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!