I am trying to execute this query in laravel and it give me the
error:SQLSTATE[42S22]: Column not found: 1054 Unknown column 'p.id' in 'field list' (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();
my posts table
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();
});
my user table
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();
AS p
inDB::table('users AS u,posts AS p')
was ignored. Maybe simply do not use an alias forposts
? or try to useCROSS JOIN
instead of comma. – Akina