【问题标题】:SQLSTATE[42S22]: Column not found: 1054 Unknown column 'p.id' in 'field list'SQLSTATE [42S22]:找不到列:1054 '字段列表'中的未知列'p.id'
【发布时间】:2021-05-13 20:29:11
【问题描述】:

我正在尝试在 laravel 中执行此查询,它给了我

错误:SQLSTATE[42S22]:未找到列:1054 '字段列表'中的未知列 'p.id'(SQL:select `p`.`id` as `post_id`, `title`, `post_content`, `image_dir`, `video_dir`, `p`.`created_at` as `post_date`, `first_name`, `last_name`, `profile_img` from `users` as `u,posts` where `title` like %mo% or `post_content` like %mo% order by `p`.`created_at` desc

$posts= DB::table('users AS u,posts AS p')
    ->select('p.id as post_id','title','post_content','image_dir','video_dir','p.created_at as post_date','first_name','last_name','profile_img')
    ->where('title', 'like', "%{$key}%")
    ->orWhere('post_content', 'like', "%{$key}%")
    ->orderBy('p.created_at', 'desc')
    ->get();

我的帖子表

Schema::create('posts', function (Blueprint $table) {
            $table->id();
            $table->string('title');
            $table->unsignedBigInteger('user_id');
            $table->foreign('user_id')->references('id')->on('users');
            $table->text('post_content')->nullable();
            $table->double('likes')->default(0);
            $table->double('dislikes')->default(0);
            $table->integer('size')->nullable();
            $table->string('image_dir')->nullable();
            $table->string('video_dir')->nullable();
            $table->timestamps();
        });

我的用户表

Schema::create('users', function (Blueprint $table) {
            $table->id();
            $table->string('first_name');
            $table->string('last_name');
            $table->string('gender');
            $table->string('phone_number')->nullable();
            $table->string('location')->nullable();
            $table->string('email')->unique();
            $table->timestamp('email_verified_at')->nullable();
            $table->string('password');
            $table->string('profile_img')->nullable();
            $table->string('cover_img')->nullable();
            $table->rememberToken();
            $table->timestamps();

【问题讨论】:

  • 你必须选择一张桌子。告诉我你要做什么,我可以帮你。
  • 如您所见,DB::table('users AS u,posts AS p') 中的片段AS p 被忽略了。也许根本不使用posts 的别名?或尝试使用CROSS JOIN 而不是逗号。
  • 你能分享你的表格架构吗?
  • 我想从 post 表中检索发布日期,并使用外键 user_id 从 users 表中检索发布帖子的用户的用户名和个人资料图像,并将其与其余部分一起发送将数据作为一条记录发布。
  • 我同意给出的答案:你应该使用加入

标签: mysql laravel eloquent


【解决方案1】:

看来您需要join

Inner Join clause

$posts= DB::table('users AS u')
    ->join('posts As p', 'u.id', '=', 'p.user_id' )
    ->select('p.id as post_id','title','post_content','image_dir','video_dir','p.created_at as post_date','first_name','last_name','profile_img')
    ->where('title', 'like', "%{$key}%")
    ->orWhere('post_content', 'like', "%{$key}%")
    ->orderBy('p.created_at', 'desc')
    ->get();

【讨论】:

  • @Akina,根据当前的问题编辑,我相信我的论点仍然成立。
猜你喜欢
  • 2019-05-28
  • 1970-01-01
  • 2015-01-19
  • 2019-10-14
  • 2021-10-31
  • 2018-10-23
  • 2017-05-05
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多