简体   繁体   English

使用Laravel 5.1检查数据库中是否存在记录

[英]Check if record exists in database using Laravel 5.1

I am inserting an xml file contents into a DB from my localstorage. 我正在从本地存储中将xml文件内容插入数据库。 However what happens is that the xml file can be updated and when its updated i need to check if the record already exists or not in my DB. 但是,发生的是该xml文件可以更新,并且在更新时我需要检查该记录是否已经存在于我的数据库中。 If it exists i need to update the record and if it doesn't exist i need to insert a new record. 如果存在,则需要更新记录,如果不存在,则需要插入新记录。 I am able to do the insert but I dont seem to find a Laravel way to do this using update method. 我能够插入,但是我似乎找不到使用更新方法执行此操作的Laravel方法。

In my xml file they is a node that doesn't change value when the xml has been updated. 在我的xml文件中,它们是一个在xml更新后不会更改值的节点。 I am thinking I must use an if statement to check against this node's value but I cant seem to get my head around this. 我在想我必须使用if语句来检查该节点的值,但是我似乎无法解决这个问题。

Below is how I am doing my insert. 以下是我的插入方式。

public function store(Request $request)
  {
    // Building directory path.
    $directory = storage_path('app/xmlentries/uploads');

    $files = File::allFiles($directory);

    foreach($files as $file) {

    $contents = $file->getContents();

    foreach((array) $contents as $content)
    {
        $simpleXml = simplexml_load_string($xml);

        $data = [
        'requisition' => $simpleXml->ExportData->Requisition['clientReqId'], //NODE THAT DOES NOT CHANGE VALUE
        'experience' => $simpleXml->ExportData->Requisition->EssentialFunction,
        'job_requirements' => $simpleXml->ExportData->Requisition->EssentialFunction,
        ],
        ];

        Vacancy::insert($data); //WHERE I AM INSERTING MY RECORD

    }

    }
    }   

How would I update the record if it already exists? 如果记录已经存在,我将如何更新?

https://laravel.com/docs/5.2/eloquent#basic-inserts https://laravel.com/docs/5.2/eloquent#basic-inserts

If you use Eloquent you don't need a "if" in your controller the "save" method will see it for you, if your PKs was correctly configured in your model 如果您使用Eloquent,则在控制器中不需要“ if”的情况下,如果在模型中正确配置了PK,则“保存”方法将为您看到

The "Vacancy" is your model right? “空缺”是您的模特吗? put every attribute in an object 将每个属性放在一个对象中

$vacancy = new Vencancy();
$vacancy->requisition = $simpleXml->ExportData->Requisition['clientReqId'];
$vacancy->save();

try it with all your attributes.... see your primary key [link] https://laravel.com/docs/5.2/eloquent#defining-models[/link] 尝试使用所有属性。...请参见主键[link] https://laravel.com/docs/5.2/eloquent#defining-models[/link]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM