Epsilon47
Epsilon47

Reputation: 838

Select from table where both columns have same value

I have the code that selects all articles. What I am doing is, I think, wrong. I am selecting all values and then I am executing them.

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

What I need to do is select only those articles that have the mentioned created_at and updated_at the same.
How could I do that on the database level? I need sth like that:

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

This code sure does not work, its just for imagine.

Upvotes: 3

Views: 61

Answers (2)

user320487
user320487

Reputation:

You only need to search on the two columns for the one value:

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

Edit:

Use whereRaw for this

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

Upvotes: 1

ali shojaei
ali shojaei

Reputation: 94

edit your code

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

Upvotes: 2

Related Questions