【发布时间】: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 表中检索发布帖子的用户的用户名和个人资料图像,并将其与其余部分一起发送将数据作为一条记录发布。
-
我同意给出的答案:你应该使用加入