Laravel 4.2多对多关系:无法从中间表读取

3

我尝试将Jeffrey Way的多对多关系教程应用到我的私人消息应用程序中,但卡住了。我正在尝试获取与用户相关联的2个对话,“haha”和“hehe”。然而,Laravel给出了以下错误:

Column not found: 1054 Unknown column 'Conversations.user_id' in 'where clause' (SQL: select * from `Conversations` where `Conversations`.`user_id` = 1)

我在我的对话表中有这些数据:
+---------+----------+
| conv_id | name     |
+---------+----------+
|       1 |     haha |
|       2 |     hehe |
+---------+----------+

在我的用户对话表中:
+----+-------------+--------+
| id | conv_id     | user_id|
+----+-------------+--------+
|  1 |           1 |      1 |
|  2 |           2 |      1 |
+----+-------------+--------+

1. 我尝试过 : 在控制器中:

User : return $this->belongsToMany('User','id');

Conversatons : return $this->hasMany('Conversations','conv_id');

但我得到的结果是 : haha 而不是 hahahehe

2. 我还尝试过 :

User : return $this->belongsToMany('User','user_conversations');

Conversatons : return $this->hasMany('Conversations','user_conversations');

但 Laravel 返回了以下错误 :

Column not found: 1054 Unknown column 'Conversations.user_conversations' in 'where clause' (SQL: select * from `Conversations` where `Conversations`.`user_conversations` = 1)

我在Laravel方面还比较新,可能会犯一些愚蠢的错误。


以下是我的代码:

模型

对话

class Conversations extends Eloquent  {

    protected $table = 'Conversations';

    protected $fillable = array('name');

    public function users(){
        return $this->belongsToMany('User');
    }

}

用户

<?php

use Illuminate\Auth\UserInterface;
use Illuminate\Auth\Reminders\RemindableInterface;

class User extends Eloquent implements UserInterface, RemindableInterface {

    ....

    public function conversations(){
        return $this->hasMany('Conversations');
    }
}

控制器

对话控制器

public function create()
    {
        $loginuser = User::find(Auth::user()->id);
        $conversations = $loginuser->conversations;
        return View::make('msgsystem.Conversations.Conversations',array('conversations'=>$conversations));
    }

迁移(在函数up()中)

用户

Schema::create('users',function($table)
        {
            $table->increments('id');
            $table->string('email')->unique();
            $table->string('password',100);
            $table->string('name',150);
            $table->string('usertype',50);
            $table->boolean('block');
            $table->string('remember_token',100);
            $table->timestamp('lastlogin_at');
            $table->timestamps();
            $table->softDeletes();
        });

对话记录

Schema::create('Conversations', function(Blueprint $table)
        {
            $table->increments('conv_id')->index();
            $table->string('name',100);
            $table->timestamps();
        });

用户对话

Schema::create('user_conversations', function(Blueprint $table)
        {
            $table->increments('id')->unsigned();
            $table->integer('conversation_id')->unsigned()->index();
            $table->foreign('conversation_id')->references('conv_id')->on('conversations')->onDelete('cascade');
            $table->integer('user_id')->unsigned()->index();
            $table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
            $table->timestamps();
        });

奖励点数用于改进代码。非常感谢!

2
如果你想要实现多对多的关系,那么你的用户(User)和对话(Conversations)模型都应该使用belongsToMany。 - Jeemusu
@Jeemusu 是的,你说得对。我正要回答我的问题,因为最近我再次查看了Way先生的教程时发现了它。也许你可以回答并进一步解释为什么hasMany-belongsToMany不符合多对多关系?谢谢! - John Evans Solachuk
2个回答

6
在您提到的多对多关系示例中,一个用户可以有多个会话,而这些会话也可以被多个用户共享。
在这种情况下,我们需要在用户模型上使用belongsToMany()方法建立关系,同时在会话模型上建立反向关系。
class User 
{
    public function conversations()
    {
        return $this->belongsToMany('Conversations');
    }
}



class Conversations 
{
    public function users()
    {
        return $this->belongsToMany('User');
    }
}

如果您需要为数据透视表使用不同的名称,或覆盖相关键,则可以将它们作为可选参数传递。

return $this->belongsToMany(
   'Conversations',          // related_table
   'user_conversations',     // pivot_table
   'user_id',                // key_1
   'conversations_id'        // key_2
);

谢谢!顺便问一下,为什么 hasMany-belongsToMany 不起作用呢?听起来是正确的,用户 hasMany 个对话,而一个对话 belongsToMany 用户,不是吗? - John Evans Solachuk
1
hasMany 中,可以将多个 foo 绑定到一个 bar 上,但在 belongsToMany 中,绑定到 barfoo 也可以绑定到另一个,比如 baz。使用 hasMany 就不合适了。一个用户可能有多个对话,而一次对话可能涉及多个用户。 - Arda

0

也许会对某些人有所帮助。我浪费了很多时间然后去查找数据库...

我忘记了在使用软删除时将“deleted_at”的默认值设置为NULL。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接