如何避免用户提交的MySQL数据库中存储的重复内容 [英] How to avoid duplicate content stored in MySQL database submitted by user

查看:111
本文介绍了如何避免用户提交的MySQL数据库中存储的重复内容的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在创建一个网站,该网站允许用户列出与其关联的5家公司.当其他用户搜索这些公司时,与该公司关联的所有用户都将显示在搜索结果中.

I am creating a site that lets users list up to 5 companies they are associated with. When other users search these companies, all users associated with that company will show up in the search results.

用户将通过文本输入字段提交公司.

The companies will be submitted by the users through a text input field.

如何避免用户提交重复的公司?例如.如果UserA提交了一个名为stackoverflow的公司,则UserB来了并且还提交了stackoverflow,则我的数据库中将有2个stackoverflows.

How do I avoid users submitting duplicate companies? E.g. if UserA submits a company called stackoverflow, then UserB comes and also submits stackoverflow, there will be 2 stackoverflows in my database.

我有3张桌子:

用户表

id |用户名|电子邮件

id|username|email

公司表

id |公司名称

UsersCompany表

id | userID | companyID

id|userID|companyID

我正在使用Laravel 5

I'm using Laravel 5

推荐答案

您可以进行简单的检查.如果该公司不存在,则创建一个新公司或将该公司附加到用户.

You can do it with a simple check. If the company does not exists create a new Company or attach the Company to the user.

我假设这些公司是用一个逗号分隔的单一文本输入形式提交的,并且您已正确设置了关系.如果没有,请选中.

I assume the companies are submitted in one single text input seperated by commas and you have setup your relations correct. If not check this.

示例:

// Inside your controller
public function post_something(Request $request)
{

    // Always good to validate
    $this->validate(....);

    // Somehow get your user model
    $user = ....

    // Get companies input and loop
    $company_names = $request->input('company_names');

    $company_names = explode(',', $company_names );

    foreach ($company_names as $company_name)
    {
        $company = Company::firstOrCreate(['company_name' => $company_name]);

        $user->companies()->attach($company);        
    }

    // Your other stuff
    //
    ....

}

这篇关于如何避免用户提交的MySQL数据库中存储的重复内容的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆