【发布时间】:2020-11-29 17:29:06
【问题描述】:
我只是一个初学者,尝试在 laravel 中使用字符串作为外键,但在获取数据时出现此错误:-
SQLSTATE[42S22]:未找到列:1054 未知列“读取”在“where 子句”中(SQL:选择
from作为 sender_id,计数(from)作为来自messages的 messages_count,其中to= d3c364bb-0982-46ba-869a-24dbb2c50aea 和read= 0 分组from)
在这里我从收到的用户联系人和一组未读消息计数中获取
public function get(){
$contacts = DB::table('received')
->where('user_id', Auth::user()->uuid)
->get();
$unreadIds = Message::select(\DB::raw('`from` as sender_id, count(`from`) as messages_count'))
->where('to', Auth::user()->uuid)
->where('read', false)
->groupBy('from')
->get();
$contacts = $contacts->map(function($contact) use ($unreadIds) {
$contactUnread = $unreadIds->where('sender_id', $contact->friends_id)->first();
$contact->unread = $contactUnread ? $contactUnread->messages_count : 0;
return $contact;
});
return response()->json($contacts);
}
收到表:-
public function up()
{
Schema::create('received', function (Blueprint $table) {
$table->engine = 'InnoDB';
$table->id();
$table->string('user_id', 36);
$table->unsignedBigInteger('friends_id');
$table->string('list_no')->nullable();
$table->string('name');
$table->timestamps();
});
}
这是我从中获取未读消息计数的地方:-
public function up()
{
Schema::table('messages', function (Blueprint $table) {
$table->engine = 'InnoDB';
$table->boolean('read')->after('to', 36)->default(false);
});
}
public function down()
{
Schema::table('messages', function (Blueprint $table) {
$table->dropColumn('read');
});
}
这是消息表
public function up()
{
Schema::create('messages', function (Blueprint $table) {
$table->engine = 'InnoDB';
$table->id();
$table->string('from', 36);
$table->string('to', 36);
$table->text('text');
$table->string('list_no')->nullable();
$table->timestamps();
});
}
谁能帮我解决这个问题。
【问题讨论】:
-
“from”是SQL中的保留表达式,不推荐使用它作为字段名! + 我在表名中发现了一个错字:
Schema::create('recieveds', function (Blueprint $table) { -
@AdamP。我在输入这个问题时犯了那个错字,
from在我不使用字符串作为外键时工作得很好 -
我建议阅读Eloquent Relationshops。不确定为什么要在迁移中定义引擎。什么版本的 MySQL 和 Laravel? MySQL 中的默认值现在是 InnoDB,因此不需要。
-
@mikeroq 我使用的是 laravel 8,我在this stack question看到了这个方法
-
@KakashiHatake 如果你注意到这个问题是从 2014 年开始的。Laravel 开发已经有很长一段时间了。