【问题标题】:Select from table where both columns have same value从两列具有相同值的表中选择
【发布时间】:2018-07-09 01:38:32
【问题描述】:

我有选择所有文章的代码。我认为我正在做的事情是错误的。我正在选择所有值,然后我正在执行它们。

Article::all()->each(function($article) {
         if ($article->created_at == $article->published_at && $article>published) {
             $article->update(['published_at' => null]);
         } 
     });

我需要做的是只选择那些具有相同 created_at 和 updated_at 的文章。
我怎么能在数据库级别做到这一点? 我需要这样的东西:

Article::where('created_at', '=', 'published_at')->where('published')->get()->each(function($article) {
           $article->update(['published_at' => null]);
     }
});

这段代码肯定行不通,只是为了想象。

【问题讨论】:

    标签: database laravel eloquent


    【解决方案1】:

    您只需要在两列中搜索一个值:

    Article::where(['created_at' => $date, 'updated_at' => $date ])->get();
    

    编辑:

    为此使用 whereRaw

    Article::whereRaw('created_at = updated_at')->get();
    

    【讨论】:

    • 我知道,但我无法访问 $date 变量。没有设置
    • 哦,我明白了,您的问题并不清楚。我会更新我的答案。
    • 是的,我承认这还不够清楚。下次我会尽量说清楚点,反正谢谢,可以了!(:
    【解决方案2】:

    编辑你的代码

    Article::all()->each(function($article) {
         if ($article->created_at == $article->published_at && $article->published) {
             $article->update(['published_at' => null]);
         } 
     });
    

    【讨论】:

    • 你写的代码不是和我一样吗?你的回答没有解决问题。
    • 不,该代码有错误 $article>published ====> $article->published
    • 哦,是的,我明白了。我只是编造的,例如我没有运行它。但这不是我的意思。
    猜你喜欢
    • 1970-01-01
    • 2020-01-03
    • 1970-01-01
    • 2014-07-14
    • 1970-01-01
    • 2022-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-11-10
    相关资源
    最近更新 更多