Laravel mysql插入+删除或更新如何?

时间:2017-06-13 08:27:32

标签: mysql laravel laravel-5 eloquent laravel-5.4

我正在废弃一个网站获取新闻并将其保存在数据库中,但是这个“工作”或功能将每小时运行一次,因此减少记录数量我将其保持在20条记录中,现在当然我不知道我想保留旧消息,因此我想要插入新查询并删除以前的查询或更新现有查询。记录数总是20,但是如何做?当然,如果我插入+删除,ID号每次都会改变。但是,如果我进行更新,我将如何告诉它更新1-20 id。

以下是数据库中的样子:

enter image description here

到目前为止这里是代码:

function oldham_chronicle(){
    $client = new Client();
    $crawler = $client->request('GET', 'http://www.oldham-chronicle.co.uk/news-features');
    $crawler->filter('div[id=content]>.teaser-50')->each(function ($node) {
        $test = $node->filter('.plain')->text();
        $test2 = $node->filter('.dateonline')->text();
        $news = new News();
        $news->title = $test;
        $news->datepublished = $test2;
        $news->save();
    });
return view('chronicle');

1 个答案:

答案 0 :(得分:3)

我建议你更新,你可以试试这个

function oldham_chronicle(){
    $client = new Client();
    $crawler = $client->request('GET', 'http://www.oldham-chronicle.co.uk/news-features');
    $crawler->filter('div[id=content]>.teaser-50')->each(function ($node, $key) {
        $test = $node->filter('.plain')->text();
        $test2 = $node->filter('.dateonline')->text();
        $id = $key + 1;
        $news = News::where('id', $id)->first();

        // if news is null
        if (!$news) {
            $news = new News();
        }

        $news->title = $test;
        $news->datepublished = $test2;
        $news->save();
    });
return view('chronicle');

我没有测试我的代码,因为我没有数据。