메시징 시스템을 구축하려고합니다. 나는 많은 관계를 가진 사용자와 대화가있는 곳.Laravel 4 일치하는 레코드가 없을 때 many to many relationship error가 발생했습니다.
사용자 모델 :
$user = User::with('conversations')->find(Auth::user()->id);
또는 :
$user = User::with('conversations')->find(1);
를
public function conversations() {
return $this->belongsToMany('Conversation');
}
회화 I는 사용자와 대화 사용자를 얻을 수 있습니다
public function users() {
return $this->belongsToMany('User');
}
은에있다
문제는 사용자가 어떤 대화를하지 않을 때 나는 예외를 얻을 수 있습니다 :
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;
}
하지만 난 여전히뿐만 아니라 예외이 방법을 얻을 .
class User extends Eloquent implements UserInterface, RemindableInterface {
function conversations(){
return $this->hasMany('Conversation');
//assuming you have a conversation model too
}
}
다음이 작업을 수행 할 수 있습니다
나는 이것이 가능한 해결책이 될 수 있습니다 생각 몇 시간 동안 프로젝트에서 멀리 걷기 후 : 클래스 사용자에
$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'가 있습니까? –