2013-12-11 1 views
1

메시징 시스템을 구축하려고합니다. 나는 많은 관계를 가진 사용자와 대화가있는 곳.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; 
} 
+0

모델에있는 관계를 게시 할 수 있습니까? –

+0

@DavidBarker 상단에 그것을 포함하도록 편집했습니다. –

+0

피벗 테이블'conversations_users'가 있습니까? –

답변

1

, 당신의 관계를 추가 대신 :

$conversations = Auth::user()->conversations; 

또는 특정 ID를 확인하는 방법은 다음과 같습니다

$conversations = User::find($id)->conversations; 

하고 현재 사용자에 연결된 모든 대화를 할 것이다 .. 당신이 대화를 가지고 후 다른 작업을 수행하기 전에 널 (null) 인 경우
이 .. 당신이 확인할 수 있습니다 ..
(예 : if(0 < $conversations->count()){ })

당신은 laravel docs


UPDATE 여기에 더 많은 정보를 찾을 수 있습니다

대신이 방법을 사용해보세요.

$user = User::has('conversation')->where('user.id','=', $id)->get(); 

업데이트 2 : 순간

// get all the conversations connected to the current user 
$my_conversations = Auth::user()->conversations; 

// generate a list of all the conversation ids 
foreach($my_conversations as $my_conversation) { 
    $conversation_ids[] = $my_conversation->id; 
} 

if(!empty($conversation_ids)) { 
    // get all the users for each conversations, via eager loading 
    $conversations = Conversation::with('User') 
     ->whereIn('id', $conversation_ids)->get(); 
} 
+1

'User :: with ('conversations')'는 이미 모델에'conversations()'메소드가 있다고 가정하고, OP가 명시한대로 공장. 이것은 해결책이 아닙니다. –

+1

"문제는 사용자가 대화를하지 않을 때입니다."- 그 이유는 대화를 먼저 받아서 해당 사용자에 대한 대화가 있는지 확인해야하기 때문입니다. – reikyoushin

+0

사용자가 특별히 "어떻게 테스트 할 수 있습니까? 사용자가 대화를 통해이를 피할 수 있습니까? 미리 감사드립니다. "이제는 그게 무슨 문제입니까? – reikyoushin

1

당신은 설득력이 관계에서 데이터의 삽입을 관리 할 수 ​​없습니다. Eloquent는 이것을 매우 쉽게 관리하고 문제를 일으킬 수있는 것처럼 보입니다.

public function create($id) 
{ 
    // Use the logged in user or the passed in user ID for user object 
    $user = isset($id) ? User::find($id) : Auth::user(); 

    // Check user exists 
    if (! $user) 
     throw new Exception('User not found'); 

    // Create a new conversation 
    $conversation = new Conversation(array(
     'creator' => $user->id 
    )); 

    $conversation->save(); 

    // Attach the user model to the conversation 
    // this method will insert all of the relational 
    // information into the pivot table for you 
    $conversation->users()->attach($user); 

    return $conversation; 
} 
+0

이 방법을 사용하는 것이 훨씬 더 좋은 방법이라는 것을 알 수 있습니다.하지만 문제가 해결되지는 않습니다. 나는 여전히 같은 예외를 얻는다. 지금까지는 if (0 <$ conversations-> count()) {}) 솔루션으로 만 피할 수 있었지만 왜 예외를 throw하고 null을 반환하지 않는지 알아 보려고합니다. –

+0

비슷한 코드에 대한 테스트를 실행 한 결과 모델에 빈 관계가 생기고로드가 불필요한 경우에도 예외가 발생하지 않습니다. 조금만 연구 해 보도록하겠습니다. 설득력있는 표현을 사용한다면 예외가되어서는 안됩니다. –

+0

질문의 맨 아래에 새로운 create 메소드를 추가했습니다. –

관련 문제