我正在嘗試回傳給定用戶參與的所有執行緒。
端點接受一個 userId 并且應該回傳一個執行緒模型的集合。
但是,在執行控制器操作時,我不斷收到此錯誤。它正在尋找一message_id列,但就此而言,我沒有在thread表或任何表上定義該列 - 使這是一個奇怪的錯誤。
SQLSTATE[42S22]: Column not found: 1054 Unknown column 'thread.message_id' in 'where
clause' (SQL: select * from `thread` where `thread`.`message_id` = 2 and
`thread`.`message_id` is not null)"
我相信我鏈接表格的方式可能有些問題,但我并不完全確定。我假設message表格的列thread_id應該參考表格上的id列,thread這就是我認為我在message下面的遷移中所做的。
我做錯了什么,我該如何解決?
這是用戶遷移:
Schema::create('users', function (Blueprint $table) {
$table->id('id');
$table->string('email')->unique();
$table->string('full_name');
$table->string('password');
});
這是執行緒遷移:
Schema::create('thread', function (Blueprint $table) {
$table->id();
$table->string('title');
});
這是訊息遷移:
Schema::create('message', function (Blueprint $table) {
$table->id();
$table->unsignedBigInteger('user_id');
$table->unsignedBigInteger('thread_id');
$table->string('body');
$table->foreign('user_id')
->references('id')
->on('users')
->onDelete('cascade');
$table->foreign('thread_id')
->references('id')
->on('thread')
->onDelete('cascade');
});
控制器動作:
public function getUserThreads($userId) {
$userParticipatedThreads = Message::findOrFail($userId);
return $userParticipatedThreads->thread;
}
訊息模型:
public function thread() {
return $this->hasMany(Thread::class);
}
端點:
[GET] http://127.0.0.1:8000/api/getUserThreads/2
Route::get('getUserThreads/{userId}', [ThreadController::class, 'getUserThreads']);
uj5u.com熱心網友回復:
您thread在 Message 類上的關系正在尋找message_id,因為這是 hasMany 關系作業的默認方式。您需要覆寫它所基于的關系的列。
public function thread() {
return $this->hasMany(Thread::class, 'id', 'thread_id');
}
但是,由于看起來訊息屬于一個單獨的執行緒(每條訊息都有一個 thread_id),那么您實際上想要的belongsTo是
public function thread() {
return $this->belongsTo(Thread::class);
}
uj5u.com熱心網友回復:
回答問題;
嘗試根據用戶 ID 回傳集合模型時,為什么會出現未找到列的錯誤?
因為您的thread表上沒有message_id定義欄位。
Schema::create('thread', function (Blueprint $table) {
$table->id();
$table->string('title');
});
AMessage屬于 a Thread,但您似乎將這種關系顛倒了。
在您的Thread模型上,定義與Message模型的關系:
public function messages()
{
return $this->hasMany(Message::class);
}
然后您可以通過用戶查詢某些訊息的存在:
$messages = Thread::whereHas('messages', function ($query) use ($userId) {
$query->where('user_id', $userId);
})->get();
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/510553.html
標籤:php拉拉维尔调试
