当没有记录匹配时,Laravel 4多对多关系错误


Laravel 4 many to many relationship error when no records match

我正在尝试构建一个消息传递系统。在那里,我与多对多关系的用户和对话。

用户型号:

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中创建新的对话,如下所示:

根据David Barker的解决方案更新了创建方法:

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;
}

在您的类User上,添加您的关系:

class User extends Eloquent implements UserInterface, RemindableInterface {
    function conversations(){
        return $this->hasMany('Conversation'); 
        //assuming you have a conversation model too
    }
}

那么你可以这样做:

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

或查找特定id:

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

并且您将拥有附加到当前用户的所有对话
在你得到对话之后。。你可以在做其他事情之前检查它是否为null
(例如:if(0 < $conversations->count()){ }

你可以在这里找到更多关于laravel文档的信息


更新:

你能试试这个吗?

$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();
}

目前您不允许Eloquent管理跨关系的数据插入。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;
}