LoginSignup
1
1

More than 1 year has passed since last update.

Laravelのエラー「SQLSTATE[42S22]: Column not found: 1054 Unknown column」を全力で解決する

Posted at

ことのあらまし

  • テーブルarticlesにアクセスしたユーザのログを取りたい、と言うことでarticle_access_logsを新規追加するよ
  • Modelも新規追加したよ
  • ControllerでSELECTしたら良く分からないエラーが出たよ
  • ER図はこんな感じ
    image2.png

エラーの内容

なんてことないエラーだと思ったんです。

SQLSTATE[42S22]: Column not found: 1054 Unknown column ・・・

article_access_logテーブルからSELECTする時のカラム名のtypoかしらね、と悠長に構えていたら

SQLSTATE[42S22]: Column not found: 1054 Unknown column 'article_access_logs.' in 'where clause' (SQL: select * from `article_access_logs` where `id` = 1 and `article_access_logs`.`` is null limit 1)

え・・・?
カラム名が空・・・?
何が起きているんだ・・・

ControllerとModel

特別なことはしていない。
詰んだかもしれないと途方に暮れる。

app\Http\Controllers\ArticleController.php
use App\Models\ArticleAccessLog;
use App\Models\Article;

class ArticleController extends Controller
{
  public function index(Request $request)
  {
    //ここは正しく取得できる
    $test1 = Article::where('id', '1')->first();
    dump($test1);

    //ここでエラーになる
    $test2 = ArticleAccessLog::where('id', '1')->first();
    dump($test2);
  }
}
app\Models\ArticleAccessLog.php
namespace App\Models;

use App\Models\BaseModel;
use Illuminate\Database\Eloquent\SoftDeletes;

class Log extends BaseModel
{
  use SoftDeletes;
  const UPDATED_AT = null;
  const DELETED_AT = null;

  protected $guarded = [
    'id', 'created_at'
  ];
}

そして解決へ・・・

Modelの設定を修正することで解決・・・

app\Models\ArticleAccessLog.php
namespace App\Models;

use App\Models\BaseModel;
use Illuminate\Database\Eloquent\SoftDeletes;

class Log extends BaseModel
{
  //↓ここがいらない
  //use SoftDeletes;
  //const UPDATED_AT = null;
  //const DELETED_AT = null;

  protected $guarded = [
    'id', 'created_at'
  ];
}

そりゃそうだ。
article_access_logsテーブルにはupdated_atカラムもdeletedカラムもない。
何にも考えずにコピペで作っていた所為だな、と反省。

そもそもの話

ログテーブルなんだからupdateもdeleteもする必要ないんですよねえ。
ちゃんと考えましょうね、自分。
こんなうっかりミスに嵌る人が出ないことを祈ります・・・。

1
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1