我試圖建立一個消息系統。我有哪些用戶和對話有多對多的關係。Laravel 4多對多關係錯誤,當沒有記錄匹配
用戶模式:
public function conversations() {
return $this->belongsToMany('Conversation');
}
對話
public function users() {
return $this->belongsToMany('User');
}
我能得到用戶和通話用戶與:
$user = User::with('conversations')->find(Auth::user()->id);
或者:
$user = User::with('conversations')->find(1);
的問題是,當用戶沒有任何交談,我得到一個例外:
SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error
in your SQL syntax; check the manual that corresponds to your MySQL server
version for the right syntax to use near ')' at line 1 (SQL: select * from
`conversations` where `id` in()) (Bindings: array ())
如何測試用戶是否有對話,以避免這種情況?提前致謝。
編輯:
我創建的ConversationsController新的對話,像這樣:
更新後,大衛·巴克的解決方案的創建方法:
public function create($id)
{
// Check user exists
$user = User::find($id);
if (! $user)
throw new Exception('User not found');
// Create a new conversation
$conversation = new Conversation();
$conversation->creator = Auth::user()->id;
$conversation->save();
// Attach the users to the conversation
$conversation->users()->attach($user);
$conversation->users()->attach(Auth::user());
return $conversation;
}
但我仍然得到例外這種方式也。
從幾個小時我覺得這可能是一個可能的解決方案的項目走開後:
$con = User::find(Auth::user()->id)->conversations;
if(0 < $con->count()) {
$conversationIds = array();
foreach ($con as $conversation) {
$conversationIds[] = $conversation->id;
}
// I THINK THIS WAS ACTUALLY THE PROBLEM
$conversations = Conversation::with('users')->whereIn('id', $conversationIds)->get();
} else {
$conversations = false;
}
您可以發佈您在模型中的關係嗎? –
@DavidBarker我編輯將它包含在頂部 –
你有一個數據透視表'conversations_users'? –